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:
import networkx as nx
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


G = nx.Graph()
N, M = map(int, input().split())
edge = [tuple(map(int, input().split())) for _ in range(M)]
G.add_edges_from(edge)
path = nx.single_source_shortest_path(G, source=1)

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

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


G = nx.Graph()
N, M = map(int, input().split())
edge = [tuple(map(int, input().split())) for _ in range(M)]
G.add_edges_from(edge)
path = nx.shortest_path(G, source=1)

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

Submission status: Time Limit Exceeded

Solution code:
def solve(string):
    from collections import deque
    n, m, *ab = map(int, string.split())
    p = [[] for _ in range(n)]
    for a, b in zip(*[iter(ab)] * 2):
        p[a - 1].append(b - 1)
        p[b - 1].append(a - 1)
    s, ans, d = deque([0]), [0] * n, [0] + [n] * (n - 1)
    while s:
        c = s.popleft()
        for t in p[c]:
            if d[c] + 1 < d[t]:
                d[t] = d[c] + 1
                ans[t] = c + 1
                if t not in s:
                    s.append(t)
    return "Yes\n" + "\n".join(map(str, ans[1:]))


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Time Limit Exceeded

Solution code:
import math
n, k = map(int,input().split())
g={}
for i in range(n):
    g[i]=[]
for i in range(k):
    a,b= map(int,input().split())
    g[a-1].append(b-1)
    g[b-1].append(a-1)
ans = [-1] * n
queue = [0]
visited = [False] * n
 

while queue:
    x = queue.pop(0)
    for n in g[x]:
        if visited[n] == False: 
            queue.append(n)
            if ans[n] == -1: 
                ans[n] = x
                visited[n] = True
 
if -1 in ans[1:]:
    print('No')
else:
    print('Yes')
    for a in ans[1:]:
        print(a+1)

Submission status: Time Limit Exceeded

Solution code:
def solve(string):
    n, m, *ab = map(int, string.split())
    p = [[] for _ in range(n)]
    for a, b in zip(*[iter(ab)] * 2):
        p[a - 1].append(b - 1)
        p[b - 1].append(a - 1)
    s, ans, d = [0], [0] * n, [0] + [n] * (n - 1)
    while s:
        c = s.pop()
        for t in p[c]:
            if d[c] + 1 < d[t]:
                d[t] = d[c] + 1
                ans[t] = c + 1
                if t not in s:
                    s.append(t)
    return "Yes\n" + "\n".join(map(str, ans[1:]))


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Time Limit Exceeded

Solution code:
def solve(string):
    n, m, *ab = map(int, string.split())
    p = [[] for _ in range(n)]
    for a, b in zip(*[iter(ab)] * 2):
        p[a - 1].append(b - 1)
        p[b - 1].append(a - 1)
    s, ans, d = [0], [0] * n, [0] + [n] * (n - 1)
    while s:
        c = s.pop()
        for t in p[c]:
            if d[c] + 1 < d[t]:
                d[t] = d[c] + 1
                ans[t] = c + 1
                s.append(t)
    return "Yes\n" + "\n".join(map(str, ans[1:]))


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from collections import deque
n , m = map(int , input().split())
g = defaultdict(list)
for i in range(m):
	u , v = map(int , input().split())
	g[u].append(v)
	g[v].append(u)
#print(g)
visited = [False]*(n+1)
a = [10**10]*(n+1)
q = deque()
q.append(1)
while q:
	node = q.popleft()
	visited[node] = True
	for ele in g[node]:
		if not visited[ele]:
			if a[ele] == 10**10: a[ele] = node
			q.append(ele)
#print(ans)
#print(a)
print("Yes")
for i in a[2:]:
	print(i)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
 
N, M = map(int,input().split())
A = [None]*M
B = [None]*M
for i in range(M):
  A[i], B[i] = map(int,input().split())

tier = [0]*2+[-1]*(N-1)
guide = [0]*(N-1)
q = [1]
count = 0

#
for t in range(N):
  
  tmp_q = []
  for i in range(M):
        
    if   ( A[i] == q[t] ):
      if ( tier[ B[i] ] == -1 or tier[ B[i] ] > tier[ q[t] ]+1 ):
        tier[ B[i] ] = tier[ q[t] ]+1
        guide[ B[i]-2 ] = A[i]
        tmp_q.append( B[i] )
        count += 1
        
    elif (  B[i]  == q[t] ):
      if ( tier[ A[i] ] == -1 or tier[ A[i] ] > tier[ q[t] ]+1 ):
        tier[ A[i] ] = tier[ q[t] ]+1
        guide[ A[i]-2 ] = B[i]
        tmp_q.append( A[i] )
        count += 1
    
  #
  tmp_q = set(tmp_q)
  q.extend( tmp_q )
  
  #print(q[t])
  #print("tier : {0}".format(tier) )
  #print("guide: {0}".format(guide) )
  #print("queue: {0}".format(q) )
  #print()

  if ( count == N-1 ):
    break
  
#
ans = 1
for i in range(N-1):
  if ( guide[i] == 0 ):
    ans = 0
    break

if ( ans == 1 ):
  print("Yes")
  for i in range(N-1):
    print( guide[i] )
  
else:
  print("No")

#

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
n,m=map(int,input().split())
s=[list(map(int,input().split())) for i in range(m)]
 
g=nx.Graph()
g.add_nodes_from([i for i in range(1,n+1)])
 
for x in s:
    g.add_edge(x[0],x[1])
di=nx.predecessor(g,source=1)
 
print("Yes")
for x in range(2,n+1):
    print(di[x][0])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
N,M = [int(i) for i in input().split()]
roads = []
for _ in range(M):
    A,B = [int(i) for i in input().split()]
    roads.append([A,B])
    roads.append([B,A])
roads = np.array(roads)
places = [0]*(N+1)
places[1] = 1
q = deque([1])
vis = [False]*(N+1)
vis[1] = True
while q:
    now = q.popleft()
    L = roads[roads[:,0] == now][:,1]
    for j in L:
        if vis[j]:
            continue
        vis[j] = True
        places[j] = now
        q.append(j)

print("Yes")
s = "\n".join(map(str, places[2:]))
print(s)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
N,M = [int(i) for i in input().split()]
roads = []
for _ in range(M):
    A,B = [int(i) for i in input().split()]
    roads.append([A,B])
    roads.append([B,A])
roads = np.array(roads)
places = [0]*(N+1)
places[1] = 1
q = deque([1])
vis = [False]*(N+1)
vis[1] = True
while q:
    now = q.pop()
    L = roads[roads[:,0] == now][:,1]
    for j in L:
        if vis[j]:
            continue
        vis[j] = True
        places[j] = now
        q.appendleft(j)

print("Yes")
s = "\n".join(map(str, places[2:]))
print(s)

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
n,m=map(int,input().split())
s=[list(map(int,input().split())) for i in range(m)]
 
g=nx.Graph()
g.add_nodes_from([i for i in range(1,n+1)])
 
for x in s:
    g.add_edge(x[0],x[1])
di=nx.predecessor(g,source=1)
 
if len(di)!=n:
    print("No");exit()
print("Yes")
for x in range(2,n+1):
    print(di[x][0])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
n,m=map(int,input().split())
s=[list(map(int,input().split())) for i in range(m)]

g=nx.Graph()
g.add_nodes_from([i for i in range(1,n+1)])

for x in s:
    g.add_edge(x[0],x[1])
di=nx.predecessor(g,source=1)

if len(di)!=n:
    print("No")
    exit()

print("Yes")
for x in range(2,n+1):
    print(di[x][0])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
AB=[set() for i in range(N+1)]
room=[0]*(N+1)
pre=[None]*(N+1)
def bfs(i):#１に到達
    Done=set()
    Done.add(i)
    d=deque([i])
    child=set()
    child.add(i)
    count=1
    while(d):
        k=d.popleft()
        if k not in child:
            count+=1
            child=child.union(Done)
        room[k]=count
        for i in AB[k]:
            if i not in Done:
                pre[i]=k
                Done.add(i)
                d.append(i)





for i in range(M):
    A,B=list(map(int,input().split()))
    AB[A].add(B)
    AB[B].add(A)

flag=True
bfs(1)
if sum(room)==0:
    print("No:")
    exit()
for i in range(2,N+1):
    if flag:
        print("Yes")
        flag=False
    if pre[i] is not None:
        print(pre[i])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
n,m=map(int,input().split())
s=[list(map(int,input().split())) for i in range(m)]
 
g=nx.Graph()
g.add_nodes_from([i for i in range(1,n+1)])
 
for x in s:
    g.add_edge(x[0],x[1])
di=nx.predecessor(g,source=1)

if len(di)!=n:
    print("No")
    exit()
 
print("Yes")
for x in range(2,n+1):
    print(di[x][0])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
g = [[] for _ in range(n+1)]
for _ in range(m):
    a, b = map(int, input().split())
    g[a].append(b)
    g[b].append(a)
d = {1: 0}
q = [1]
for i in q:
    s = set(g[i]) - set(d)
    d.update(dict.fromkeys(s, i))
    q.extend(s)
print('Yes')
for i in range(2, n+1):
    print(d[i])

Submission status: Time Limit Exceeded

Solution code:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p = [[] for _ in range(n)]
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p[a-1].append(b)
    p[b-1].append(a)
d = [1, ]
con = {}
l = 0
for _ in range(1, n):
    for i, k in enumerate(p[1:]):
        if i+2 in d:continue
        if d[l] in k:
            d.append(i+2)
            con[i+2] = d[l]
    if len(d) > l:
        l += 1
    else:
        break
if len(con) < n-1:
    print('No')
else:
    print('Yes')
    for i in range(n-1):
        print(con[i+2])

Submission status: Time Limit Exceeded

Solution code:
import copy

#メイン部
N,M=map(int,input().split())

V=list(range(1,N+1))
H={v:set() for v in V}
L={v:None for v in V}

for i in range(M):
    v,w=map(int,input().split())
    H[v].add(w)
    H[w].add(v)

X=set()
Y={V[0]}

while X!=Y:
    Z=Y-X
    X=copy.deepcopy(Y)
    
    for v in Z:
        K=[u for u in H[v] if u not in Y]
        for x in K:
            Y.add(x)
            L[x]=v

if set(V)==X:
    print("Yes")
    for i in range(2,N+1):
        print(L[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
def bfs():
  d = [0]*n
  que = deque([])
  que.append(0)
  d[0] = 1 #到達済み
  for i in range(10**10):
    if que == []:
      break
    now = que.popleft() 
    if d == [1]*n: #全て到達したら終わり
      break
    for next in g[now]: #部屋1から行ける場所で回す
      if d[next] == 0:
        que.append(next)
        d[next] = 1
        direction[next] = now +1
        
n,m = map(int,input().split())
g = [[] for i in range(n)]
direction = [0]*n
for i in range(m):
  a,b = map(int,input().split())
  g[a-1].append(b-1)
  g[b-1].append(a-1)
  
bfs()
print('Yes')
print(*direction[1:],sep='\n')

Submission status: Time Limit Exceeded

Solution code:
import copy
import collections

def Neighbohood(V,E,v):
    H=[]
    for w in V:
        if ((v,w) in E) or ((w,v) in E):
            H.append(w)

    return H

def bfs(V,E):
    W=[ v for v in V]
    Q=collections.deque([W[0]])
    searched = { v: False for v in W}
    searched[W[0]] = True
    L={v:None for v in W}
    n=1
    
    while len(Q) != 0:
        v=Q.popleft()
        Nei=Neighbohood(V,E,v)

        D=[x for x in Nei if searched[x]==False]
        
        for w in D:
            Q.append(w)
            L[w]=v
            searched[w] = True
            n+=1
            
    return (L,n)

#メイン部
N,M=map(int,input().split())

V=list(range(1,N+1))

E=[]
for i in range(M):
    v,w=map(int,input().split())
    E.append((v,w))

(L,n)=bfs(V,E)
if N==n:
    print("Yes")
    for i in range(2,N+1):
        print(L[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
def bfs():
  d = [0]*n
  que = deque([])
  que.append(0)
  d[0] = 1 #到達済み
  for i in range(10**10):
    if que == []:
      break
    now = que.popleft() 
    if d == [1]*n: #全て到達したら終わり
      break
    for next in g[now]: #部屋1から行ける場所で回す
      if d[next] == 0:
        que.append(next)
        d[next] = 1
        direction[next] = now 
        
n,m = map(int,input().split())
g = [[] for i in range(n)]
direction = [0]*n
for i in range(m):
  a,b = map(int,input().split())
  g[a-1].append(b-1)
  g[b-1].append(a-1)
  
bfs()
print('Yes')
for i in range(1,n):
  print(direction[i]+1)

Submission status: Time Limit Exceeded

Solution code:
import copy

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

V=list(range(1,N+1))
K={v:set() for v in V}
L={v:None for v in V}
    
for i in range(M):
    v,w=map(int,input().split())

    K[v].add(w)
    K[w].add(v)


X=set()
Y={V[0]}

while X!=Y:
    Z=copy.deepcopy(Y-X)
    X=copy.deepcopy(Y)

    for v in Z:
        for n in K[v]:
            if n not in Y:
                Y.add(n)
                L[n]=v
                

if set(V)==X:
    print("Yes")
    for i in range(2,N+1):
        print(L[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
AB=[set() for i in range(N+1)]
node_list=[None]*(N+1)
class node():
    def __init__(self,i):
        self.node=i
        self.prev=None
def bfs(i):#１に到達
    Done=set()
    Done.add(i)
    d=deque([i])

    while(d):

        kako = set()
        k=d.popleft()
        if node_list[k] is None:
            n = node(k)
        else:
            n=node_list[k]
        for i in AB[k]:
            if i not in Done:
                jk=node(i)
                jk.prev=n
                node_list[i]=jk
                Done.add(i)
                d.append(i)
                if i==1:
                    return True,jk


        node_list[k]=n
    return False,0




for i in range(M):
    A,B=list(map(int,input().split()))
    AB[A].add(B)
    AB[B].add(A)
flag1=True
for i in range(2,N+1):
    flag,jk=bfs(i)
    if flag:
        if flag1:
            print("Yes")
            flag1=False

        while(jk.prev.node!=i):
            jk=jk.prev
        print(jk.node)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
AB=[set() for i in range(N+1)]
node_list=[None]*(N+1)
class node():
    def __init__(self,i):
        self.node=i
        self.prev=None
def bfs(i):#１に到達
    Done=set()
    Done.add(i)
    d=deque([i])
    child = set()
    child.add(i)
    while(d):

        kako = set()
        k=d.popleft()
        if node_list[k] is None:
            n = node(k)
        else:
            n=node_list[k]
        for i in AB[k]:
            if i not in Done:
                jk=node(i)
                jk.prev=n
                node_list[i]=jk
                Done.add(i)
                d.append(i)
                child.add(i)
                if i==1:
                    return True,jk


        node_list[k]=n
    return False,0




for i in range(M):
    A,B=list(map(int,input().split()))
    AB[A].add(B)
    AB[B].add(A)
flag1=True
for i in range(2,N+1):
    flag,jk=bfs(i)
    if flag:
        if flag1:
            print("Yes")
            flag1=False

        while(jk.prev.node!=i):
            jk=jk.prev
        print(jk.node)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
AB=[set() for i in range(N+1)]
node_list=[None]*(N+1)
class node():
    def __init__(self,i):
        self.node=i
        self.prev=None
def bfs(i):#１に到達
    Done=set()
    Done.add(i)
    d=deque([i])
    count = 1
    a = set()
    a.add(i)
    bro = {0: a}
    second=False
    while(d):

        kako = set()
        k=d.popleft()
        if node_list[k] is None:
            n = node(k)
        else:
            n=node_list[k]
        for i in AB[k]:
            if i not in Done:
                jk=node(i)
                jk.prev=n
                node_list[i]=jk
                kako.add(i)
                Done.add(i)
                d.append(i)
                if i==1:
                    return True,jk

        if k  in bro[count-1]:
            if count not in bro:
                bro[count]=kako
            else:
                bro[count] = bro[count].union(kako)
        else:#入ってなかった場合
            count+=1

            if count not in bro:
                bro[count]=kako
            else:
                bro[count] = bro[count].union(kako)
        node_list[k]=n
    return False,0




for i in range(M):
    A,B=list(map(int,input().split()))
    AB[A].add(B)
    AB[B].add(A)
flag1=True
for i in range(2,N+1):
    flag,jk=bfs(i)
    if flag:
        if flag1:
            print("Yes")
            flag1=False

        while(jk.prev.node!=i):
            jk=jk.prev
        print(jk.node)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys,pprint

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

print(paths, file=sys.stderr)
result = [0]*N

searchroom = []
nextsearch = []
searchroom.append(1)
while len(searchroom) > 0:
    print(searchroom,paths,file=sys.stderr)
    for n in searchroom:
        j = 0
        while j < len(paths):
            s = paths[j]
            if n in s:
                print(s,"exist", file=sys.stderr)
                print(paths,s,file=sys.stderr)
                paths.remove(s)
                j -= 1
                print(paths,s,file=sys.stderr)
                s.remove(n)
                t = s.pop()
                if result[t-1] == 0:
                    result[t-1] = n
                    nextsearch.append(t)
            j += 1
    searchroom = nextsearch.copy()
    nextsearch.clear()

print(result,file=sys.stderr)

# no判定
for i in result[1:]:
    if i == 0:
        print("No")
        sys.exit()
print("Yes")    
for i in result[1:]:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
from dataclasses import dataclass
from collections import deque


@dataclass
class Query:
    now: int
    prev: int
    cost: int


N, M = map(int, input().split())
E = [[] for _ in range(N + 1)]

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

res = [-1 for _ in range(N + 1)]
cost = [float('inf') for _ in range(N + 1)]
cost[1] = 0

queue = deque()

for next in E[1]:
    queue.append(Query(next, 1, 1))

while len(queue):
    q = queue.popleft()
    if cost[q.now] > q.cost:
        res[q.now] = q.prev
        cost[q.now] = q.cost

    for next in E[q.now]:
        if cost[next] > q.cost + 1:
            queue.append(Query(next, q.now, q.cost + 1))

for r in res[2:]:
    if r == -1:
        print('No')
        exit()

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

Submission status: Time Limit Exceeded

Solution code:
import math
import queue
def dijkstra(n, w):
    ans=[math.inf]*n
    done=[]
    done.append(1)
    q=queue.Queue()
    for i in w[1]:
        q.put(i)
        ans[int(i)-1]=1
        done.append(i)
    while not q.empty():
        now=q.get()
        for i in w[now]:
            if i not in done:
                q.put(i)
                done.append(i)
                ans[i-1]=now
        if max(ans)!=math.inf:
            break
    return ans

s = list(map(int,input().split()))
n=s[0]
m=s[1]
mapping=[[] for i in range(n+1)]
for i in range(m):
    s = list(map(int, input().split()))
    mapping[s[0]].append(s[1])
    mapping[s[1]].append(s[0]) 

ans=dijkstra(n,mapping)
if not math.inf in ans[1:]:
    print('Yes')
    for i in ans[1:]:
        print(i)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
def bfs():
  global direction
  d = [0]*n
  que = deque([])
  que.append(0)
  d[0] = 1 #到達済み
  for i in range(10**10):
    if que == []:
      break
    now = que.popleft() 
    if d == [1]*n: #全て到達したら終わり
      break
    for next in g[now]: #部屋1から行ける場所で回す
      if d[next] == 0:
        que.append(next)
        d[next] = 1
        direction[next] = now 
        
n,m = map(int,input().split())
g = [[] for i in range(n)]
direction = [0]*n
for i in range(m):
  a,b = map(int,input().split())
  g[a-1].append(b-1)
  g[b-1].append(a-1)
  
bfs()
print('Yes')
for i in range(1,n):
  print(direction[i]+1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs():
  global direction
  d = [0]*n
  que = deque([])
  que.append(0)
  d[0] = 1 #到達済み
  for i in range(10**10):
    if que == []:
      break
    now = que.popleft() 
    if d == [1]*n: #全て到達したら終わり
      break
    for next in g[now]: #部屋1から行ける場所で回す
      if d[next] == 0:
        que.append(next)
        d[next] = 1
        direction[next] = now 
  

n,m = map(int,input().split())
g = [[] for i in range(n)]
direction = [0]*n
for i in range(m):
  a,b = map(int,input().split())
  a -= 1
  b -= 1
  g[a].append(b)
  g[b].append(a)
  
bfs()
print('Yes')
for i in range(1,n):
  print(direction[i]+1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs():
  global direction
  d = [0]*n
  que = deque([])
  que.append(0)
  d[0] = 1 #到達済み
  while que:
    now = que.popleft() 
    if d == [1]*n: #全て到達したら終わり
      break
    for next in g[now]: #部屋1から行ける場所で回す
      if d[next] == 0:
        que.append(next)
        d[next] = 1
        direction[next] = now 
  

n,m = map(int,input().split())
g = [[] for i in range(n)]
direction = [0]*n
for i in range(m):
  a,b = map(int,input().split())
  a -= 1
  b -= 1
  g[a].append(b)
  g[b].append(a)
  
bfs()
print('Yes')
for i in range(1,n):
  print(direction[i]+1)

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
room, route_count = map(int,input().split())

G = nx.Graph()
G.add_nodes_from(range(1,room+1))
G.add_edges_from([list(map(int,input().split())) for _ in range(route_count)])

is_end = False
for i in range(2, room+1):
  if nx.has_path(G,source=i, target=1)==False:
    is_end = True
    break

if is_end:
  print('No')
else:
  print('Yes')
  shortest_path_dict = nx.single_target_shortest_path(G, target=1)
  for i in range(2,room+1):
    print(shortest_path_dict[i][1])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
room, route_count = map(int,input().split())
G = nx.Graph()
G.add_nodes_from(range(1,room+1))
G.add_edges_from([list(map(int,input().split())) for _ in range(route_count)])
if all([nx.has_path(G,source=i, target=1) for i in range(1, room+1)]):
  print('Yes')
  shortest_path_dict = nx.single_target_shortest_path(G, target=1)
  for i in range(2,room+1):
    print(shortest_path_dict[i][1])
else:
  print('No')

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
room, route_count = map(int,input().split())
route = [list(map(int,input().split())) for _ in range(route_count)]

G = nx.Graph()
G.add_nodes_from(range(1,room+1))
G.add_edges_from(route)
shortest_path_dict = nx.single_target_shortest_path(G, target=1)
if len(shortest_path_dict)<room:
  print('No')
else:
  print('Yes')
  for i in range(2,room+1):
    print(shortest_path_dict[i][1])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
room, route_count = map(int,input().split())

G = nx.Graph()
G.add_nodes_from(range(1,room+1))
G.add_edges_from([list(map(int,input().split())) for _ in range(route_count)])
shortest_path_dict = nx.shortest_path(G, target=1)
if len(shortest_path_dict)<room:
  print('No')
else:
  print('Yes')
  for i in range(2,room+1):
    print(shortest_path_dict[i][1])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
room, route_count = map(int,input().split())
route = [list(map(int,input().split())) for _ in range(route_count)]

G = nx.Graph()
G.add_nodes_from(range(1,room+1))
G.add_edges_from(route)
shortest_path_dict = nx.shortest_path(G, target=1)
if len(shortest_path_dict)<room:
  print('No')
else:
  print('Yes')
  for i in range(2,room+1):
    print(shortest_path_dict[i][1])

Submission status: Time Limit Exceeded

Solution code:
import sys

N, M = list(map(int, input().split()))
E = [[] for i in range(N)]

for i in range(M):
    a, b = list(map(int, input().split()))
    a -= 1; b -= 1
    E[a].append(b)
    E[b].append(a)
    
par = [-1] * N
q = [(0, 0)]

while q:
    v, p = q.pop(0)
    
    if par[v] != -1: continue
    par[v] = p
    
    for u in E[v]:
        q.append((u, v))
    
for p in par[1:]:
    if p == -1:
        print('No')
        sys.exit()
        
print('Yes')
for p in par[1:]:
    print(p+1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

N, M = map(int, input().split())
A = [0]*M
B = [0]*M
for i in range(M):
    A[i], B[i] = map(int, input().split())

C = [1]
C_old = [0]
D = list(range(M))
D_old=[0]*M
E = [0]*N
F = [0]*N
#print("{}".format(D))
for i in range(M):
    if not 0 in F[1:N]:
        break
    #print("{}".format(i))
    C_old=[0]
#    print("{}".format(C))
#    print("{}".format(D))
    for j in D:
        #print("A={},B={},j={}".format(A[j],B[j],j))
        if A[j] in C:
            if E[B[j]-1]==0:
                C_old.append(B[j])
                E[B[j]-1]=A[j]
                F[B[j]-1]=1
                D_old[j]=1
             #else:
            #     E[B[j]-1]=min(A[j],E[B[j]-1])
            #print("D={}".format(D))
            #print("{}".format(E))

        elif B[j] in C:
             if E[A[j]-1]==0:
                 C_old.append(A[j])
                 E[A[j]-1]=B[j]
                 F[A[j]-1]=1
                 D_old[j]=1
             #else:
            #     E[A[j]-1]=min(B[j],E[A[j]-1])
             #print("D={}".format(D))
             #print("{}".format(E))

    C.extend(C_old[1:])
    D=[i for i in D if D_old[i]== 0]


if not 0 in F[1:N]:
    print("Yes")
    for i in range(N-1):
        print("{}".format(E[i+1]))

else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**8)

def dfs(v,cnt):
    dist[v]=cnt
    for nv in graph[v]:
        if dist[nv]<=cnt+1:
            continue 
        guide[nv]=v
        dfs(nv,cnt+1)

n,m=map(int,input().split())
graph=[[] for _ in range(n+1)]
dist=[float("inf") for _ in range(n+1)]
guide=[0 for _ in range(n+1)]

for _ in range(m):
    a,b=map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)

dfs(1,0)

print("Yes")
print(*guide[2:],sep="\n")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

N, M = map(int, input().split())
A = [0]*M
B = [0]*M
for i in range(M):
    A[i], B[i] = map(int, input().split())

C = [1]
C_old = [0]
D = list(range(M))
D_old=[0]*M
E = [0]*N
F = [0]*N
#print("{}".format(D))
for i in range(M):
    if not 0 in F[1:N]:
        break
    #print("{}".format(i))
    C_old=[0]
    #print("{}".format(C))
    #print("{}".format(D))
    for j in D:
        #print("A={},B={},j={}".format(A[j],B[j],j))
        if A[j] in C:
            C_old.append(B[j])
            if E[B[j]-1]==0:
                E[B[j]-1]=A[j]
                F[B[j]-1]=1
                D_old[j]=1
             #else:
            #     E[B[j]-1]=min(A[j],E[B[j]-1])
            #print("D={}".format(D))
            #print("{}".format(E))

        elif B[j] in C:
             C_old.append(A[j])
             if E[A[j]-1]==0:
                 E[A[j]-1]=B[j]
                 F[A[j]-1]=1
                 D_old[j]=1
             #else:
            #     E[A[j]-1]=min(B[j],E[A[j]-1])
             #print("D={}".format(D))
             #print("{}".format(E))

    C.extend(C_old[1:])
    D=[i for i in D if D_old[i]== 0]


if not 0 in F[1:N]:
    print("Yes")
    for i in range(N-1):
        print("{}".format(E[i+1]))

else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

N, M = map(int, input().split())
A = [0]*M
B = [0]*M
for i in range(M):
    A[i], B[i] = map(int, input().split())

C = [1]
C_old = [0]
D = list(range(M))
D_old=[0]*M
E = [0]*N
F = [0]*N
#print("{}".format(D))
for i in range(M):
    if not 0 in F[1:N]:
        break
    #print("{}".format(i))
    C_old=[0]
    #print("{}".format(C))
    #print("{}".format(D))
    for j in D:
        #print("A={},B={},j={}".format(A[j],B[j],j))
        if A[j] in C:
            C_old.append(B[j])
            if E[B[j]-1]==0:
                E[B[j]-1]=A[j]
                F[B[j]-1]=1
                D_old[j]=1
             #else:
            #     E[B[j]-1]=min(A[j],E[B[j]-1])
            #print("D={}".format(D))
            #print("{}".format(E))

        elif B[j] in C:
             C_old.append(A[j])
             if E[A[j]-1]==0:
                 E[A[j]-1]=B[j]
                 F[A[j]-1]=1
                 D_old[j]=1
             #else:
            #     E[A[j]-1]=min(B[j],E[A[j]-1])
             #print("D={}".format(D))
             #print("{}".format(E))

    C.extend(C_old)
    D=[i for i in D if D_old[i]== 0]


if not 0 in F[1:N]:
    print("Yes")
    for i in range(N-1):
        print("{}".format(E[i+1]))

else:
    print("No")