Problem:


Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 2 \times 10^5

1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.



Sample input:
4 4
1 2
2 3
3 4
4 2


Sample output:
Yes
1
2
2

Submission status: Time Limit Exceeded

Solution code:
def retrun_index(c_lis):
    return [i for i, x in enumerate(c_lis) if x==1]

n, m = map(int, input().split())
lis = [0]*(n+1)
c = [[0]*(n+1) for i in range(n+1)]
for i in range(m):
    a, b = map(int, input().split())
    c[a][b] = 1
    c[b][a] = 1
depth = [[1]]
i = 0
co = 1
se = set(depth[0])
while co < n:
    te = [k for j in depth[i] for k, x in enumerate(c[j]) if x==1]
    te = set(te) - se
    if len(te) == 0:
        break
    co += len(te)
    se = te | se
    depth.append(list(te))
    i += 1

    
if co != n:
    print("No")
else:
    print("Yes")
    for i in range(1, len(depth)):
        te = depth[i-1]
        for j in depth[i]:
            t = c[j]
            for k in te:
                if t[k]==1:
                    lis[j] = k
                    break
    for i in lis[2:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
def retrun_index(c_lis):
    return [i for i, x in enumerate(c_lis) if x==1]

n, m = map(int, input().split())
lis = [1, 1] + [0]*(n-1)
c = [[0]*(n+1) for i in range(n+1)]
for i in range(m):
    a, b = map(int, input().split())
    c[a][b] = 1
    c[b][a] = 1
ind = retrun_index(c[1])
for i in ind:
    lis[i] = 1
i = 0
while True:
    if i>=len(ind):
        break
    t = ind[i]
    te = retrun_index(c[t])
    for j in te:
        if lis[j] == 0:
            lis[j] = t
            ind.append(j)
    i += 1

    
if lis.count(0) > 0:
    print("No")
else:
    print("Yes")
    for i in lis[2:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N,M = list(map(int,input().split()))
MAX = 1000000000
S = []
Room = [MAX for i in range(N)]#2 - N
Room[0] = 0
ACCESS = [0 for i in range(N-1)]
for _ in range(M):
    a,b = list(map(int,input().split()))
    S.append([a,b])
    S.append([b,a])
for i in S:
    if i[0] == 1:
        Room[i[1]-1] = 1
        ACCESS[i[1]-2] = 1
        #S.remove(i)
depth = 1
while max(Room) > MAX/2:
    for i in range(len(Room)):
        if Room[i] ==depth:
            for j in S:
                if (j[0] == i+1)*(Room[j[1]-1]>MAX/2):
                    Room[j[1]-1] = depth+1
                    ACCESS[j[1]-2] = i+1
    depth += 1
print('Yes')
for i in ACCESS:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import time
N, M = list(map(int, input().split()))

to = [[] for i in range(10**5)]

for _ in range(M):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)

MAX = 10**10


q = []
dist = [MAX for i in range(N)]
pre = [-1 for i in range(N)]

dist[0] = 0
q.append(0)

while len(q) != 0:
    time.sleep(0.3)
    v = q.pop(0)
    for u in to[v]:
        if (dist[u] != MAX):
            continue
        dist[u] = dist[v] + 1
        pre[u] = v
        q.append(u)
print('Yes')
for v in pre[1:]:
    print(v + 1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N, M  = list(map(int, input().split()))

network = [[] for _ in range(N+1)]

res = np.zeros((N+1), dtype="int32")
distance = np.full((N+1), N+1)
distance[1] = 0


for _ in range(M):
    i, j = list(map(int, input().split()))
    network[i].append(j)
    network[j].append(i)


from collections import deque


n = 0
s = []
queue = deque([1])
while n < N:
    top = queue.popleft()
    s.append(top)
    for i in network[top]:
        if i not in s:
            queue.append(i)
            if distance[i] > distance[top]+1:
                distance[i] = distance[top]+1
                res[i] = top

    n += 1


print("Yes")  
for r in res[2:]:
    print(r)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N, M  = list(map(int, input().split()))


network = {}
for i in range(N+1):
    network[i] = list()
res = np.zeros((N+1), dtype="int32")
distance = np.full((N+1), N+1)
distance[1] = 0


for _ in range(M):
    i, j = list(map(int, input().split()))
    network[i].append(j)
    network[j].append(i)

s = []

from collections import deque


n = 0
queue = deque([1])
while n < N:
    top = queue.popleft()
    s.append(top)
    for i in network[top]:
        if i not in s:
            queue.append(i)
            if distance[i] > distance[top]+1:
                distance[i] = distance[top]+1
                res[i] = top

    n += 1


print("Yes")  
for r in res[2:]:
    print(r)

Submission status: Time Limit Exceeded

Solution code:
[N, M] = list(map(int, input().split()))
X = [0]*N
A = []
B = []

for i in range(M):
    x = list(map(int, input().split()))
    A.append(x[0])
    B.append(x[1])

position = set()
np = set()
position.add(1)


for i in range(1, N):
    for j in range(M):
        if A[j] in position and X[B[j] - 1] == 0:
            X[B[j] - 1] = A[j]
            np.add(B[j])
        if B[j] in position and X[A[j] - 1] == 0:
            X[A[j] - 1] = B[j]
            np.add(A[j])
    position.clear()
    for k in np:
        position.add(k)
    np.clear()

print('Yes')
[print(X[i]) for i in range(1, N)]

Submission status: Time Limit Exceeded

Solution code:
[N, M] = list(map(int, input().split()))
X = [0]*N
A = []
B = []

for i in range(M):
    x = list(map(int, input().split()))
    A.append(x[0])
    B.append(x[1])

position = set()
np = set()
position.add(1)


for i in range(1, N):
    for j in range(M):
        if A[j] in position and X[B[j] - 1] == 0:
            X[B[j] - 1] = A[j]
            np.add(B[j])
        if B[j] in position and X[A[j] - 1] == 0:
            X[A[j] - 1] = B[j]
            np.add(A[j])
    for k in np:
        position.add(k)
    np.clear()

print('Yes')
[print(X[i]) for i in range(1, N)]

Submission status: Time Limit Exceeded

Solution code:
class Graph():
    def __init__(self, directed:bool, nord_count:int):
        self.directed = directed
        self.degree = [0 for _ in range(nord_count)]
        self.edges = [[] for _ in range(nord_count)]
        self.edge_count = 0
        self.nord_count = nord_count


    def insert_edge(self, x, y, directed:bool):
        edge = EdgeNode(y=y, weight=None, edge_node = None)
        self.edges[x].append(edge)
        self.degree[x] += 1
        if directed == False:
            self.insert_edge(y, x, True)
        else:
            self.edge_count += 1

    def print_graph(self):
        for i in range(self.nord_count):
            for edge in self.edges[i]:
                print(i, edge.y)

class EdgeNode():
    def __init__(self, y, weight, edge_node):
        self.y = y
        self.weight = weight
        self.edge_node = edge_node

N, M = [int(i) for i in input().split()]
graph = Graph(directed=False, nord_count = N)
for i in range(M):
    A, B  = [int(i) for i in input().split()]
    graph.insert_edge(x=A-1, y=B-1, directed=False)

signpost = [None for _ in range(N)]
found = [False for _ in range(N)]
found[0] = True
current_node = 0
previous_node = 0
queue = [[previous_node, current_node]]
while len(queue) != 0:
    previous_node, current_node = queue.pop(0)
    signpost[current_node] = previous_node
    for edge in graph.edges[current_node]:
        if found[edge.y] == False:
            found[edge.y] = True
            queue.append([current_node, edge.y])
signpost = signpost[1:]
if None in signpost:
    print('No')
else:
    print('Yes')
for i in signpost:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
class Graph():
    def __init__(self, directed:bool, nord_count:int):
        self.directed = directed
        self.degree = [0 for _ in range(nord_count)]
        self.edges = [[] for _ in range(nord_count)]
        self.edge_count = 0
        self.nord_count = nord_count


    def insert_edge(self, x, y, directed:bool):
        edge = EdgeNode(y=y, weight=None, edge_node = None)
        self.edges[x].append(edge)
        self.degree[x] += 1
        if directed == False:
            self.insert_edge(y, x, True)
        else:
            self.edge_count += 1

    def print_graph(self):
        for i in range(self.nord_count):
            for edge in self.edges[i]:
                print(i, edge.y)

class EdgeNode():
    def __init__(self, y, weight, edge_node):
        self.y = y
        self.weight = weight
        self.edge_node = edge_node

N, M = [int(i) for i in input().split()]
graph = Graph(directed=False, nord_count = N)
for i in range(M):
    A, B  = [int(i) for i in input().split()]
    graph.insert_edge(x=A-1, y=B-1, directed=False)

signpost = [None for _ in range(N)]
found = [False for _ in range(N)]
found[0] = True
current_node = 0
previous_node = 0
queue = [[previous_node, current_node]]
while len(queue) != 0:
    previous_node, current_node = queue.pop(0)
    if signpost[current_node] == None:
        signpost[current_node] = previous_node
        for edge in graph.edges[current_node]:
            if found[edge.y] == False:
                found[edge.y] = True
                queue.append([current_node, edge.y])
signpost = signpost[1:]
if None in signpost:
    print('No')
else:
    print('Yes')
for i in signpost:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
class Graph():
    def __init__(self, directed:bool, nord_count:int):
        self.directed = directed
        self.degree = [0 for _ in range(nord_count)]
        self.edges = [[] for _ in range(nord_count)]
        self.edge_count = 0
        self.nord_count = nord_count


    def insert_edge(self, x, y, directed:bool):
        edge = EdgeNode(y=y, weight=None, edge_node = None)
        self.edges[x].append(edge)
        self.degree[x] += 1
        if directed == False:
            self.insert_edge(y, x, True)
        else:
            self.edge_count += 1

    def print_graph(self):
        for i in range(self.nord_count):
            for edge in self.edges[i]:
                print(i, edge.y)

class EdgeNode():
    def __init__(self, y, weight, edge_node):
        self.y = y
        self.weight = weight
        self.edge_node = edge_node

N, M = [int(i) for i in input().split()]
graph = Graph(directed=False, nord_count = N)
for i in range(M):
    A, B  = [int(i) for i in input().split()]
    graph.insert_edge(x=A-1, y=B-1, directed=False)

signpost = [None for _ in range(N)]
found = [False for _ in range(N)]

current_node = 0
previous_node = 0
queue = [[previous_node, current_node]]
while len(queue) != 0:
    previous_node, current_node = queue.pop(0)
    if signpost[current_node] == None:
        signpost[current_node] = previous_node
        for edge in graph.edges[current_node]:
            if found[edge.y] == False:
                found[edge.y] = True
                queue.append([current_node, edge.y])
signpost = signpost[1:]
if None in signpost:
    print('No')
else:
    print('Yes')
for i in signpost:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
class Graph():
    def __init__(self, directed:bool, nord_count:int):
        self.directed = directed
        self.degree = [0 for _ in range(nord_count)]
        self.edges = [[] for _ in range(nord_count)]
        self.edge_count = 0
        self.nord_count = nord_count


    def insert_edge(self, x, y, directed:bool):
        edge = EdgeNode(y=y, weight=None, edge_node = None)
        self.edges[x].append(edge)
        self.degree[x] += 1
        if directed == False:
            self.insert_edge(y, x, True)
        else:
            self.edge_count += 1

    def print_graph(self):
        for i in range(self.nord_count):
            for edge in self.edges[i]:
                print(i, edge.y)

class EdgeNode():
    def __init__(self, y, weight, edge_node):
        self.y = y
        self.weight = weight
        self.edge_node = edge_node

N, M = [int(i) for i in input().split()]
graph = Graph(directed=False, nord_count = N)
for i in range(M):
    A, B  = [int(i) for i in input().split()]
    graph.insert_edge(x=A-1, y=B-1, directed=False)

signpost = [None for _ in range(N)]
current_node = 0
previous_node = 0
queue = [[previous_node, current_node]]
while len(queue) != 0:
    previous_node, current_node = queue.pop(0)
    if signpost[current_node] == None:
        signpost[current_node] = previous_node
        for edge in graph.edges[current_node]:
            queue.append([current_node, edge.y])
signpost = signpost[1:]
if None in signpost:
    print('No')
else:
    print('Yes')
for i in signpost:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
class Graph():
    def __init__(self, directed:bool, nord_count:int):
        self.directed = directed
        self.degree = [0 for _ in range(nord_count)]
        self.edges = [[] for _ in range(nord_count)]
        self.edge_count = 0
        self.nord_count = nord_count


    def insert_edge(self, x, y, directed:bool):
        edge = EdgeNode(y=y, weight=None, edge_node = None)
        self.edges[x].append(edge)
        self.degree[x] += 1
        if directed == False:
            self.insert_edge(y, x, True)
        else:
            self.edge_count += 1

    def print_graph(self):
        for i in range(self.nord_count):
            for edge in self.edges[i]:
                print(i, edge.y)

class EdgeNode():
    def __init__(self, y, weight, edge_node):
        self.y = y
        self.weight = weight
        self.edge_node = edge_node

N, M = [int(i) for i in input().split()]
graph = Graph(directed=False, nord_count = N)
for i in range(M):
    A, B  = [int(i) for i in input().split()]
    graph.insert_edge(x=A-1, y=B-1, directed=False)

signpost = [None for _ in range(N)]
queue = []
for edge in graph.edges[0]:
    queue.append([0, edge])
while len(queue) != 0:
    current_node, edge = queue.pop(0)
    if signpost[edge.y] == None:
        signpost[edge.y] = current_node
        for next_edge in graph.edges[edge.y]:
            if signpost[next_edge.y] == None:
                queue.append([edge.y, next_edge])
signpost = signpost[1:]
if None in signpost:
    print('No')
else:
    print('Yes')
for i in signpost:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
class Graph():
    def __init__(self, directed:bool, nord_count:int):
        self.directed = directed
        self.degree = [0 for _ in range(nord_count)]
        self.edges = [[] for _ in range(nord_count)]
        self.edge_count = 0
        self.nord_count = nord_count


    def insert_edge(self, x, y, directed:bool):
        edge = EdgeNode(y=y, weight=None, edge_node = None)
        self.edges[x].append(edge)
        self.degree[x] += 1
        if directed == False:
            self.insert_edge(y, x, True)
        else:
            self.edge_count += 1

    def print_graph(self):
        for i in range(self.nord_count):
            for edge in self.edges[i]:
                print(i, edge.y)

class EdgeNode():
    def __init__(self, y, weight, edge_node):
        self.y = y
        self.weight = weight
        self.edge_node = edge_node

N, M = [int(i) for i in input().split()]
graph = Graph(directed=False, nord_count = N)
for i in range(M):
    A, B  = [int(i) for i in input().split()]
    graph.insert_edge(x=A-1, y=B-1, directed=False)

signpost = [None for _ in range(N)]
queue = []
for edge in graph.edges[0]:
    queue.append([0, edge])
while len(queue) != 0:
    current_node, edge = queue.pop(0)
    if signpost[edge.y] == None:
        signpost[edge.y] = current_node
    for next_edge in graph.edges[edge.y]:
        if signpost[next_edge.y] == None:
            queue.append([edge.y, next_edge])
signpost = signpost[1:]
if None in signpost:
    print('No')
else:
    print('Yes')
for i in signpost:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline
from collections import deque

N,M = [int(x) for x in input().split()]
next =[set() for _ in range(N+1)]

for i in range(M):
    A,B = [int(x) for x in input().split()]
    next[A].add(B)
    next[B].add(A)

opened = deque()
opened.append(1)

closed = [False] * (N+1)
prev = [-1] * (N+1)
prevlen = [float('inf')] * (N+1)
prevlen[1] = 0

while len(opened) != 0:
    target = opened.popleft()
    closed[target] = True
    for n in next[target]:
        if closed[n] == False:
            opened.append(n)
        if prevlen[n] > prevlen[target]+1:
            prev[n] = target
            prevlen[n] = prevlen[target]+1


print('Yes')
# for i in range(2,N+1):
#     print(prev[i])
print(" ".join([str(x) for x in prev[2:]]))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline

from collections import deque

N,M = [int(x) for x in input().split()]
next =[set() for _ in range(N+1)]

for i in range(M):
    A,B = [int(x) for x in input().split()]
    next[A].add(B)
    next[B].add(A)

opened = deque()
opened.append(1)

closed = [False] * (N+1)
prev = [-1] * (N+1)
prevlen = [float('inf')] * (N+1)
prevlen[1] = 0

while len(opened) != 0:
    target = opened.popleft()
    closed[target] = True
    for n in next[target]:
        if closed[n] == False:
            opened.append(n)
        if prevlen[n] > prevlen[target]+1:
            prev[n] = target
            prevlen[n] = prevlen[target]+1


print('Yes')
for i in range(2,N+1):
    print(prev[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N,M = [int(x) for x in input().split()]
next =[set() for _ in range(N+1)]

for i in range(M):
    A,B = [int(x) for x in input().split()]
    next[A].add(B)
    next[B].add(A)

opened = deque()
opened.append(1)

#closed = set()
closed = [False] * (N+1)
prev = [-1] * (N+1)
prevlen = [float('inf')] * (N+1)
prevlen[1] = 0

while len(opened) != 0:
    target = opened.popleft()
    #closed.add(target)
    closed[target] = True
    for n in next[target]:
        # if n not in closed:
        if closed[n] == False:
            opened.append(n)
        if prevlen[n] > prevlen[target]+1:
            prev[n] = target
            prevlen[n] = prevlen[target]+1


print('Yes')
for i in range(2,N+1):
    print(prev[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N,M = [int(x) for x in input().split()]
next =[set() for _ in range(N+1)]

for i in range(M):
    A,B = [int(x) for x in input().split()]
    next[A].add(B)
    next[B].add(A)

opened = deque()
opened.append(1)

closed = set()
prev = [-1] * (N+1)
prevlen = [float('inf')] * (N+1)
prevlen[1] = 0

while len(opened) != 0:
    target = opened.popleft()
    closed.add(target)
    for n in next[target]:
        if n not in closed:
            opened.append(n)
        if prevlen[n] > prevlen[target]+1:
            prev[n] = target
            prevlen[n] = prevlen[target]+1


print('Yes')
for i in range(2,N+1):
    print(prev[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
g = [[] for _ in range(n)] # 隣接リスト

for _ in range(m):
    a, b = [int(x) for x in input().split()]
    g[a - 1].append(b - 1)
    g[b - 1].append(a - 1)

from collections import deque

def bfs(u):
    queue = deque([u])
    d = [None] * n # uからの距離の初期化
    d[u] = 0 # 自分との距離は0
    while queue:
        v = queue.popleft()
        for i in g[v]:
            if d[i] is None:
                d[i] = d[v] + 1
                queue.append(i)
    return d

# 0からの各頂点の距離
d = bfs(0)
print('Yes')
for i in range(n - 1):
    print(d.index((d[i + 1]) - 1) + 1)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
g = [[] for _ in range(n)] # 隣接リスト

for _ in range(m):
    a, b = [int(x) for x in input().split()]
    g[a - 1].append(b - 1)
    g[b - 1].append(a - 1)

from collections import deque

def bfs(u):
    queue = deque([u])
    d = [None] * n # uからの距離の初期化
    d[u] = 0 # 自分との距離は0
    while queue:
        v = queue.popleft()
        for i in g[v]:
            if d[i] is None:
                d[i] = d[v] + 1
                queue.append(i)
    return d

# 0からの各頂点の距離
d = bfs(0)
print('Yes')
for i in range(n - 1):
    print(d.index((d[i + 1]) - 1) + 1)

Submission status: Time Limit Exceeded

Solution code:
import queue
N, M = map(int, input().split())


path = [[] for i in range(N + 1)]


for i in range(M):
    a,b = map(int,input().split())
    path[a].append(b)
    path[b].append(a)


flag_directions = [-1 for i in range(N + 1)]

q = queue.Queue()
for p in path[1]:
    q.put((1, p))

while not q.empty():
    current, to = q.get()
    if flag_directions[to] == -1:
        flag_directions[to] = current 
        for next_room in path[to]:
            q.put((to, next_room))


print('Yes')
for f in flag_directions[2:]:
    print(f)

Submission status: Time Limit Exceeded

Solution code:
import queue
N,M=map(int,input().split())
ans=[0] * N
q=queue.Queue()
q.put(1)

import sys
s = sys.stdin.readlines()
G=[[] for _ in range(N)]

for e in s:
  a, b = map(int, e.split())
  G[a-1].append(b)
  G[b-1].append(a)
  
c=0

while 0 in ans[1:N]:
  r=q.get()
  for i in G[r-1]:
    if ans[i-1]==0:
      ans[i-1]=r
      q.put(i)

print("Yes")
for i in range(N-1):
  print(ans[i+1])

Submission status: Time Limit Exceeded

Solution code:
import networkx

n, m = map(int, input().split())
g = networkx.Graph()
g.add_nodes_from(list(range(n)))
for i in range(1, m + 1):
    a, b = map(int, input().split())
    g.add_edge(a, b)
print("Yes")

path = networkx.single_source_shortest_path(g,1)
for i in range(2, n + 1):
    print(path[i][-2])

Submission status: Time Limit Exceeded

Solution code:
import queue
N,M=map(int,input().split())
ans=[0] * N
q=queue.Queue()
q.put(1)

import sys
s = sys.stdin.readlines()

c=0

while c!=N-1:
  r=q.get()
  for e in s:
    L, R = map(int, e.split())
    if L==r and ans[R-1]==0 and R!=1:
      ans[R-1]=r
      q.put(R)
      c+=1
    if R==r and ans[L-1]==0 and L!=1:
      ans[L-1]=r
      q.put(L)
      c+=1
    
print("Yes")
for i in range(N-1):
  print(ans[i+1])

Submission status: Time Limit Exceeded

Solution code:
import sys, os, re
from pprint import pprint
from math import sin, cos, sqrt, radians

n, m = list(map(int, sys.stdin.readline().strip().split()))
g = [[] for x in range(n)]

for i in range(m):
    x, y = map(int, sys.stdin.readline().strip().split())
    x -= 1
    y -= 1
    g[x].append(y)
    g[y].append(x)

if [] in g:
    print("No")
    exit(0)

ans = {0: -1}

while len(ans) < n:
    flag = False
    for k, v in list(ans.items()):
        for node in g[k]:
            if node not in ans:
                ans[node] = k
                flag = True
    if flag == False:
        break

print("Yes")
for i in range(1, n):
    print(ans[i]+1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N, M = list(map(int, input().split()))

edges = []

for i in range(M) :
  a, b = list(map(int, input().split()))
  if(a < b) :
    edges.append([a, b])
  else :
    edges.append([b, a])
  
destination = [0 for i in range(N)]
length = [0 for i in range(N)]
rest = N-1

for a, b in edges :
  if(a == 1) :
    if(length[b-1] == 0) :
      length[b-1] = 1
      destination[b-1] = 1
      rest -= 1

i = 1
while(rest > 0) :
  pos = []
  for l in range(len(length)) :
    if(i == length[l]) :
      pos.append(l+1)
  for p in pos :
    for a, b in edges :
      if(a == p) :
        if(length[b-1] == 0) :
          length [b-1] = length[a-1]+1
          destination[b-1] = a
          rest -= 1
      if(b == p) :
        if(length[a-1] == 0) :
          length[a-1] = length[b-1]+1
          destination[a-1] = b
          rest -= 1
  i += 1

print("Yes")
for d in destination[1:] :
  print(d)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n,m=map(int,input().split())
node=[[] for _ in range(n)]

for _ in range(m):
    a,b=map(lambda x:int(x)-1,input().split())
    node[a].append(b)
    node[b].append(a)
    
#print(node)


seen=[False]*n
depth=[0]*n
todo=deque([])
todo.append(0)
    
    
while len(todo)>0:
    p=todo[0]
    
    seen[p]=True
    to=node[p]
    for i in to:
        if seen[i]:continue
        if not (i in todo):
            depth[i]+=depth[p]+1
            todo.append(i)
    todo.popleft()



#print(depth)

sekai=[]

for i in range(1,n):
    for j in node[i]:
        if depth[j]<depth[i]:
            sekai.append(j+1)
            break

if len(sekai)!=n-1:
    print('No')
else:
    print("Yes")
    for a in sekai:
        print(a)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n,m=map(int,input().split())
node=[[] for _ in range(n)]

for _ in range(m):
    a,b=map(lambda x:int(x)-1,input().split())
    node[a].append(b)
    node[b].append(a)
    
#print(node)


seen=[False]*n
depth=[0]*n
todo=[]
todo.append(0)
    
    
while len(todo)>0:
    p=todo[0]
    
    seen[p]=True
    to=node[p]
    for i in to:
        if seen[i]:continue
        if not (i in todo):
            depth[i]+=depth[p]+1
            todo.append(i)
    todo.pop(0)



#print(depth)

sekai=[]

for i in range(1,n):
    for j in node[i]:
        if depth[j]<depth[i]:
            sekai.append(j+1)
            break
#print(sekai)

if len(sekai)!=(n-1):
    print('No')
else:
    print("Yes")
    for a in sekai:
        print(a)

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
a=[]
b=[]
C=[1]
D=[1]
s=[0 for i in range(n)]
s[0] = "Yes"
 
for i in range(m):
  c,d=map(int,input().split())
  a.append(c)
  b.append(d)
 
def Next(be):
  A=[a[i] for i in range(len(a)) if a[i] == be or b[i] == be]
  B=[b[i] for i in range(len(b)) if b[i] == be or a[i] == be]
  A=[i for i in A if i != be]
  B=[i for i in B if i != be]
  A.extend(B)
  for i in A:
    if s[i-1] == 0:
      s[i-1] = be
  return A
 
while True:
  if s.count(0)==0:
    break
  for i in C:
    D=Next(i)
    C = D
for i in s:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
import sys
import socket

hostname = socket.gethostname()

if hostname == 'F451C':
    sys.stdin = open('d1.in')


def read_int_list():
    return list(map(int, input().split()))


def read_str_list():
    return input().split()


def read_int():
    return int(input())


def read_str():
    return input()


def solve():
  N, M = read_int_list()
  A = [0] * M
  B = [0] * M
  for i in range(M):
    A[i], B[i] = read_int_list()

  res = [0] * (N - 1)
  done = set()
  l = set([1])
  for i in range(N):
    l2 = set()
    for k in range(M):
      for t in l:
        if t == A[k]:
          if B[k] not in l and B[k] not in done:
            l2.add(B[k]) 
            res[B[k] - 2] = A[k]

        if t == B[k]:
          if A[k] not in l and A[k] not in done:
            l2.add(A[k])
            res[A[k] - 2] = B[k]

    # done = done.union(set(l))
    done.update(l)
    l = l2

  return res


def main():
    res = solve()
    print('Yes', *res, sep='\n')


main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import socket

hostname = socket.gethostname()

if hostname == 'F451C':
    sys.stdin = open('d1.in')


def read_int_list():
    return list(map(int, input().split()))


def read_str_list():
    return input().split()


def read_int():
    return int(input())


def read_str():
    return input()


def solve():
  N, M = read_int_list()
  A = [0] * M
  B = [0] * M
  for i in range(M):
    A[i], B[i] = read_int_list()

  res = [0] * (N - 1)
  done = []
  l = [1]
  for i in range(N):
    l2 = []
    for k in range(M):
      for t in l:
        if t == A[k]:
          if B[k] not in l and B[k] not in done:
            l2.append(B[k]) 
            res[B[k] - 2] = A[k]

        if t == B[k]:
          if A[k] not in l and A[k] not in done:
            l2.append(A[k])
            res[A[k] - 2] = B[k]

    done += l
    l = l2

  return res


def main():
    res = solve()
    print('Yes', *res, sep='\n')


main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split(' '))
c = [[] for i in range(n)]
r = [0] * n
q = deque()
for i in range(m):
    a, b = map(int, input().split(' '))
    c[a - 1].append(b - 1)
    c[b - 1].append(a - 1)
q.append([0] + c[0])
while(len(q) > 0):
    g = q.popleft()
    ix = g.pop(0)
    for i in g:
        r[i] = ix + 1 if r[i] == 0 else r[i]
        if len(c[i]) > 0:
            t = [i] + [j for j in c[i] if r[j] == 0]
            if len(t) > 1:
                q.append(t)
jg = 'Yes' if r.pop(0) > 0 else 'No'
print(jg)
for i in r:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import queue
n, m = map(int, input().split(' '))
c = [[] for i in range(n)]
r = [0] * n
q = queue.Queue()
for i in range(m):
    a, b = map(int, input().split(' '))
    c[a - 1].append(b - 1)
    c[b - 1].append(a - 1)
q.put([0] + c[0])
while(q.qsize() > 0):
    g = q.get()
    ix = g.pop(0)
    for i in g:
        r[i] = ix + 1 if r[i] == 0 else r[i]
        if len(c[i]) > 0:
            t = [i] + [j for j in c[i] if r[j] == 0]
            if len(t) > 1:
                q.put(t)
jg = 'Yes' if r.pop(0) > 0 else 'No'
print(jg)
for i in r:
    print(i)