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:
from collections import Counter 
from collections import defaultdict
from collections import deque
from functools import reduce
import math
import itertools
import heapq
import numpy as np
import sys
sys.setrecursionlimit(10**6)

#n=int(input())
#n,m=list(map(int,input().split()))
#a=list(map(int,input().split()))
ceil=lambda x,y: (x+y-1)//y
input_list = lambda : list(map(int,input().split()))



def search_color(edge,next_edge,color_check):
    ind=color_check[edge].index(True)
    color_check[edge][ind]=False
    color_check[next_edge][ind]=False
    return ind+1
#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node,c):
    
    side_num_arr=list(map(lambda x :len(x),node))
    l=max(side_num_arr)
    #print(l)
    queue=[-1 for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    color_check=[[True for _ in range(l)] for _ in range(n)]
    color=[-1 for _ in range(n-1)]
    last_ind=1
    while last_ind<n:
        
        if now>=n:
            return []
        check[queue[now]]=True
        if side_num_arr[queue[now]]<=0:
            now+=1
            continue
        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if side_num_arr[edge]<=0 or check[edge]==True:
                continue
            side_num_arr[edge]-=1
            side_num_arr[queue[now]]-=1
            queue[last_ind]=edge
            last_ind+=1
            check[edge]=True
            
            ans[edge]=queue[now]
            #color[ind]=search_color(queue[now],edge,color_check)
        now+=1
    return ans



n,m=input_list()
node=[[] for _ in range(n)]
for i in range(m):
    u,v=input_list()
    u-=1
    v-=1
    node[u].append([v,i])
    node[v].append([u,i])

#print(np.array(node))
check=[-1 for _ in range(n)]
check[0]=0
ans=bfs(0,n,node,check)
if len(ans)==0:
    print("No")
    exit()

print("Yes")
for each in ans[1:]:
    print(each+1)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from collections import deque

n,m = map(int,readline().split())
g = [[] * n for i in range(n)]
for i in range(m):
    u, v = map(int,readline().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)
    
ans = [-1]*n
from collections import deque

que = deque()
que.append((0,1))
chk = [False]*n
chk[0] =True
while que:
    now,p = que.popleft()
    if all(chk):
      break
    for i in g[now]:
        if not chk[i]:
          ans[i] = p
          chk[i] = True
          que.append((i,i+1))


for i in ans[1:]:
  if i == -1:
    print('No')
    exit()
print('Yes')
for i in ans[1:]:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M = [int(x) for x in input().split()]
INF = 10**9
dist = [INF] * N
ans = [-1] * N
to = [set() for _ in range(N)]
for _ in range(M):
    A, B = [int(x)-1 for x in input().split()]
    to[A].add(B)
    to[B].add(A)
bfs = [(0, 0, -1)]
while len(bfs):
    cur, d, p = bfs.pop()
    if d < dist[cur]:
        dist[cur] = d
        ans[cur] = p
    for v in to[cur]:
        if d+1 < dist[v]:
            bfs.append((v, d+1, cur))
    d += 1
print('Yes')
for a in ans[1:]:
    print(a+1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

explored = [0]

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

q = deque()
parent = 0
for k in graph[0]:
    ans[k] = 0
    q.append(k)
    explored.append(k)
ans[0] = 0
while len(q) != 0:
    now = q.popleft()
    parent = now
    for node in graph[now]:
        if node not in explored:
            q.append(node)
            ans[node] = parent
            explored.append(node)

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

Submission status: Time Limit Exceeded

Solution code:
import math
from queue import Queue

n, m = [int(i) for i in input().split()]

root = [[0 for _ in range(n+1)] for _ in range(n+1)]

for i in range(m):
    a, b = [int(i) for i in input().split()]
    root[a][b] = 1
    root[b][a] = 1


check = [0 for _ in range(n+1)]
check[1] = 1

q = Queue()
q.put(1)

while ( not q.empty() ):
    now = q.get()
    for i in range(1,n+1):
        if(root[now][i] == 1 and check[i] == 0):
            check[i] = now
            q.put(i)

flag = 1
for i in range(2, n+1):
    if(check[i] == 0):
        flag = 0

if(flag == 1):
    print("Yes")
    for j in range(2, n + 1):
        print(check[j])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop, heapify
def trace(s, t, ancestors):
    route = [t]
    c = t
    while True:
        a = ancestors[c]
        assert a is not None, 'Failed to trace'
        route.append(a)
        if a == s:
            break
        c = ancestors[c]
    route.reverse()
    return route


def dijkstra(s, t, links):
    heap = [(*l, s) for l in links[s]]
    heapify(heap)
    visited = set()
    ancestors = [None] * N
    while heap:
        cost, node, ancestor = heappop(heap)
        if node in visited:
            continue
        visited.add(node)
        ancestors[node] = ancestor
        if node == t:
            return cost, trace(s, t, ancestors)
        for cost2, node2 in links[node]:
            if node2 not in visited:
                heappush(heap, (cost + cost2, node2, node))
    return float('inf'), None

N, M = map(int, input().split())
links = [set() for _ in range(N)]
for _ in range(M):
    x, y = map(int, input().split())
    links[x-1].add((1, y-1))
    links[y-1].add((1, x-1))
ans = [0]*N
for i in range(1, N):
    tmp = dijkstra(0, i, links)
    if tmp == float("inf"):
        print("No")
        exit()
    ans[i] = tmp[1][-2]+1
print("Yes")
for i in range(1,N):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))

n,m=getNM()
a=[]
b=[]
c=[0]*(n+1)
for i in range(m):
    a1,b1=getNM()
    a.append(a1)
    b.append(b1)
    if a1==1:
        c[b1]=1
    elif b1==1:
        c[a1]=1


for i in range(1,n):
    for j in range(m):
        #print(c)
        if c[a[j]]==i and c[b[j]]==0:
            c[b[j]]=a[j]
        elif c[b[j]]==i and c[a[j]]==0:
            c[a[j]]=b[j]

if 0 in c[2:]:
    print('No')
    exit()
print('Yes')
for i in range(n-1):
    print(c[2:][i])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
def run():
    N, M = map(int, sysread().split())
    to = [[] for _ in range(N+1)]
    AB = list(map(int, read().split()))
    for i in range(M):
        a = AB[2*i]
        b = AB[2*i+1]
        to[a].append(b)
        to[b].append(a)

    seen = [False] * (N+1)
    stack = []
    seen[1] = True
    heappush(stack, (0, 1, 0))# (distance, node, prev)
    INF = 1<<64
    mark = [INF] * (N+1)


    while stack:
        dist, current, prev = heappop(stack)
        seen[current] = True
        if mark[current] == INF:
            mark[current] = prev
        for next in to[current]:
            if not seen[next]:
                heappush(stack, (dist+1, next, current))

    print('Yes')
    mark = [str(val) for val in mark]
    print('\n'.join(mark[2:]))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    # https://atcoder.jp/contests/abc070/tasks/abc070_d
    # https://atcoder.jp/contests/abc070/submissions/11681543
    from heapq import heapify, heappop, heappush
    
    N ,M= map(int,input().split())
    inf = 10 ** 17
    
    
    def dijkstra_heap(start, edge):
        # 始点から各頂点への最短距離(頂点番号:0~N-1)
        d = [inf] * N
        used = [False] * N
        d[start] = 0
        used[start] = True
        edgelist = []
        # a:重み(//), b:次の頂点(%)
        for a, b in edge[start]:
            heappush(edgelist, a * (10 ** 6) + b)
    
        while len(edgelist):
            # まだ最短距離が決まっていない頂点の中から最小の距離のものを探す
            minedge = heappop(edgelist)
            if used[minedge % (10 ** 6)]:
                continue
            node = minedge % (10 ** 6)
            d[node] = minedge // (10 ** 6)
            used[node] = True
    
            for e in edge[node]:
                if not used[e[1]]:
                    heappush(edgelist, (e[0] + d[node]) * (10 ** 6) + e[1])
        return d
    
    
    # N:頂点数   W:辺数
    edge = [[] for i in range(N)]
    # edge[i] : iから出る道の[重み,行先]の配列
    for _ in range(M):
        a, b= map(int, input().split())
        edge[a - 1].append((1, b - 1))
        edge[b - 1].append((1, a - 1))
    
    d = dijkstra_heap(0, edge)
    
    def main():
        mark=[0]+[-1]*(N-1)
        times=[0]+[-1]*(N-1)
        cur=1
        for i in range(1,N):
            if d[i]==1:
                mark[i]=0
                times[i]=cur
        cur+=1
        cnt=False
        while True:
            if -1 not in mark:
                break
            for i in range(1,N):
                if d[i]==cur:
                    cnt=True
                    for k in range(len(edge[i])):
                        if times[edge[i][k][1]]==cur-1:
                            mark[i]=edge[i][k][1]
                            times[i]=cur
                            cnt+=1
                            break
                        else:
                            if k==len(edge[i])-1:
                                return False
            if not cnt:
                return False
            else:
                cur+=1
                cnt=False
        
        return mark[1:]
    
    if main():
        print('Yes')
        for i in main():
            print(i+1)
    else: print('No')
        



    
resolve()

Submission status: Time Limit Exceeded

Solution code:
import math
#n=input()
n,m=map(int,input().split())
#a=list(map(int,input().split()))
l=[list(map(int,input().split())) for i in range(m)]

ll=[[] for i in range(n)]

for i in range(m):
    ll[l[i][0]-1].append(l[i][1])
    ll[l[i][1]-1].append(l[i][0])

lll=[0 for i in range(n)]
lll[0]=-1
lt=[False for i in range(n)]
lt[0]=True
r=0


while all(lt)!=True:
    if r==0:
        for i in ll[0]:
            lll[i-1]=1
            lt[i-1]=True
        r=ll[0]
    else:
        rr=[]
        for i in r:
            for j in ll[i-1]:
                if lll[j-1]==0:
                    lll[j-1]=i
                    lt[j-1]=True
        for i in r:
            rr+=ll[i-1]
        r=rr
print("Yes")
for i in range(1,n):
    print(lll[i])

Submission status: Time Limit Exceeded

Solution code:
n, m = list(map(int, input().split()))
edge = [[] for k in range(n)]
for k in range(m):
    a, b = list(map(int, input().split()))
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)

start = 0

from collections import deque
que = deque([start])
done = {start}
depth = [1e9]  * n
depth[start] = 0
parents = [-1] * n
while True:
    if len(que) == 0:
        break
    now = que.popleft()
    dep = depth[now]
    for node in edge[now]:
        if node not in done:
            if dep < depth[node]:
                depth[node] = dep + 1
                parents[node] = now
                que.append(node)
    done.add(now)
#     print(now)
if max(depth) == 1e9:
    print("No")
else:
    print("Yes")
    for k in range(1, n):
        print(parents[k] + 1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse.csgraph import csgraph_from_dense, shortest_path
n, m, *AB = map(int, open(0).read().split())
graph = [[10**9]*n for _ in range(n)]
for a, b in zip(AB[::2], AB[1::2]):
    graph[a-1][b-1] = 1
    graph[b-1][a-1] = 1
G = csgraph_from_dense(graph)
d, p = shortest_path(G, indices=0, method='D', return_predecessors=1)
if np.any(d > 10**9-1):
    print('No')
else:
    print('Yes')
    print(*map(lambda x: int(x)+1, p[1:]), sep='\n')

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
marks = {i+1:-1 for i in range(n)}
roots = {i+1:[] for i in range(n)}
count = 0
for i in range(m):
    a,b = map(int,input().split())
    roots[a].append(b)
    roots[b].append(a)

before_room = 1
searchs = [{'root':roots[1], 'mark':1}]
while searchs != []:
    next_search = []
    for search in searchs:
        for root in search['root']:
            new_root = []
            if marks[root] == -1:
                marks[root] = search['mark']
                count += 1
                new_root += roots[root]
            next_search.append({'root':roots[root], 'mark':root})
    if count >= n-1:
        break
    searchs = next_search[:]

del marks[1]
print('Yes')
for v in marks.values():
    print(v)

Submission status: Time Limit Exceeded

Solution code:


def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    p = [-1] * n
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
            if d[v]+cost[v][j] < d[j]:
                p[j] = v
            
            d[j] = min(d[j], d[v]+cost[v][j])
    return d, p

def main():
    N, M = map(int, input().split())
    cost = [[float("inf") for i in range(N)] for i in range(N)]

    for i in range(M):
        a, b = map(int, input().split())
        cost[a-1][b-1] = 1
        cost[b-1][a-1] = 1
    
    d, p = dijkstra(0, N, M, cost)

    ans = [x + 1 for x in p[1:]]

    print('Yes')
    print(*ans, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(4100000)
input = sys.stdin.readline
from collections import deque

n,m = map(int,input().split())
g = [[] * n for i in range(n)]
for i in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    g[u].append(v)
    g[v].append(u)
    
ans = [-1]*n
cnt = [n]*n
def dfs(now, prev,c):
    for next in g[now]:
        if next != prev and next!=0:
          if cnt[next] > c:
            ans[next] = now+1
            cnt[next] = c
            dfs(next, now,c+1)
            
from collections import deque

que = deque()
que.append((0,1))
chk = [False]*n
chk[0] =True
while que:
    now,p = que.popleft()
    if all(chk):
      break
    for i in g[now]:
        if not chk[i]:
          ans[i] = p
          chk[i] = True
          que.append((i,i+1))


for i in ans[1:]:
  if i == -1:
    print('No')
    exit()
print('Yes')
for i in ans[1:]:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
import collections

n, m = map(int, input().split())
dic = collections.defaultdict(lambda:[])
for _ in range(m):
  a, b = map(int, input().split())
  dic[a].append(b)
  dic[b].append(a)
  
ans = [None] * n
bfs = [(1,0)]
visited = set()
while bfs:
  now, prev = bfs.pop(0)
  if now in visited:
    continue
  visited.add(now)
  if ans[now-1] == None:
    ans[now-1] = prev
  bfs.extend([(i, now) for i in dic[now]])

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# スペース区切りの整数の入力
N, M = map(int, input().split())
# 文字列の入力
#s = input()
#開業されたN個要素を受け付ける
#list = [input() for i in range(N)]
input_list = [list(map(int, input().split())) for i in range(M)]
flg = [0 for i in range(N)]

#print(input_list)
#print(flg)

flg[0] = 1
ans_list = [0 for i in range(N)]
now_depth = [1]
depth = 1

while(0 in flg):
    #print(depth)
    #print(now_depth)
    next_depth = []
    for i in now_depth:
        for j in input_list:
            if i in j:
                if j[0] == i:
                    if flg[j[1]-1] == 0:
                        flg[j[1]-1] = 1
                        ans_list[j[1]-1] = i
                        next_depth.append(j[1])
                elif j[1] == i:
                    if flg[j[0]-1] == 0:
                        flg[j[0]-1] = 1
                        ans_list[j[0]-1] = i
                        next_depth.append(j[0])
    depth = depth+1
    now_depth = next_depth

print("Yes")
for i in ans_list:
    if not i == 0:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
g = {}
for i in range(M):
  a, b = map(int, input().split())
  if a in g.keys():
    g[a].append(b)
  else:
    g[a] = [b]
  if b in g.keys():
    g[b].append(a)
  else:
    g[b] = [a]
ans = [0 for _ in range(N+1)]
#print(g)
tmp = [1]
while 0 in ans[2:]:
  #print(ans)
  for i in tmp:
    #print('i',i)
    next = g[i]
    #print('next',next)
    for j in next:
      if ans [j] == 0:
        ans[j] = i
  tmp = next
print('Yes')
for i in range(2,N+1):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18
# ----------------------------------------------------------- #

n, m = Is()
AB = TIR(m)
C = [[INF]*n for _ in range(n)]
for a, b in AB:
    a -= 1
    b -= 1
    C[a][b] = 1
    C[b][a] = 1

def dijkstra_back(s, t, n, w, cost):
    # sからtへの最短経路の経路復元
    prev = [s] * n  # 最短経路の直前の頂点
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0

    while True:
        v = -1
        for i in range(n):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
            break
        used[v] = True

        for i in range(n):
            if d[i] > d[v] + cost[v][i]:
                d[i] = d[v] + cost[v][i]
                prev[i] = v

    path = [t]
    while prev[t] != s:
        path.append(prev[t])
        prev[t] = prev[prev[t]]
    path.append(s)
    path = path[::-1]
    return path

ANS = [INF]*n
for i in range(n):
    if ANS[i] != INF:
        continue
    path = dijkstra_back(0, i, n, m, C)
    for j, x in enumerate(path):
        if j == 0:
            continue
        else:
            ANS[x] = path[j-1]

print("Yes")
for ans in ANS[1:]:
    print(ans+1)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def abc168_d():
    N, _ = map(int, readline().split())
    adj_mtx = [[False] * (N+1) for _ in range(N+1)]  # 0行0列は使わない
    for ln in readlines():
        a, b = map(int, ln.split())
        adj_mtx[a][b] = adj_mtx[b][a] = True

    labels = [-1] * (N+1)  # -1は未訪問
    labels[0] = labels[1] = 0  # index=0はずっと未訪問だけど0にしておく

    from collections import deque
    que = deque([1])

    while que:
        k = que.popleft()
        for x in range(N+1):
            if not adj_mtx[k][x]: continue  # つながっていない
            if labels[x] != -1: continue  # 訪問済み
            labels[x] = k  # 行先表示が確定
            que.append(x)  # キューに追加

    if -1 in labels:
        print('No')
        return
    else:
        print('Yes')
        print(*labels[2:], sep='\n')

abc168_d()

Submission status: Time Limit Exceeded

Solution code:
# Problem D - Double Dots

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

    if b in graph_list:
        graph_list[b].append(a)
    else:
        graph_list[b] = [a]

# initialization
visit_list = [0]*N
distance_list = [float("INF")]*N
distance_list[0] = 0
visit_queue = [1]
queue_count = 1

# bfs search
while queue_count>0:
    v = visit_queue.pop()
    queue_count -= 1

    graph = graph_list[v]
    for n in graph:
        if distance_list[v-1]+1<distance_list[n-1]:
            distance_list[n-1] = distance_list[v-1] + 1
            visit_list[n-1] = v
            visit_queue.append(n)
            queue_count += 1

# output
print("Yes")
for i in range(1, N):
    print(visit_list[i])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
edge = {i: [] for i in range(1, n+1)}
reached = {i: 0 for i in range(2, n+1)}
guide = {i: 0 for i in range(2, n+1)}
for _ in range(m):
    a, b = map(int, input().split())
    edge[a].append(b)
    edge[b].append(a)

# print(edge)
edge_dict = {e: 1 for e in edge[1]}
while sum(reached.values()) < n-1:
    new_dict = {}
    for e, now in edge_dict.items():
        if e != 1 and reached[e] == 0:
            reached[e] = 1
            guide[e] = now
            for next in edge[e]:
                new_dict[next] = e
    edge_dict = new_dict.copy()

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

Submission status: Time Limit Exceeded

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

d = {}

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

for i in range(M):
    a, b = map(int,input().split())
    d[a].append(b)
    d[b].append(a)
que = [1]
checked = set()
ans = {1:-1}
while que and len(ans) != N:
    now = que.pop(0)
    for h in d[now]:
        if not h in ans:
            ans[h] = now
            if len(ans) == N:
                break
            que.append(h)
    
if len(ans) == N:
    print('Yes')
    for i in range(N-1):
        print(ans[i+2]) 
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
n, m = list(map(int, input().split()))
edge = [[] for k in range(n)]
for k in range(m):
    a, b = list(map(int, input().split()))
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)

start = 0

from collections import deque
que = deque([start])
done = {start}
depth = [1e9]  * n
depth[start] = 0
parents = [-1] * n
while True:
    if len(que) == 0:
        break
    now = que.popleft()
    dep = depth[now]
    for node in edge[now]:
        if node not in done:
            que.append(node)
            if dep < depth[node]:
                depth[node] = dep + 1
                parents[node] = now
    done.add(now)
#     print(now)
if max(depth) == 1e9:
    print("No")
else:
    print("Yes")
    for k in range(1, n):
        print(parents[k] + 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    n, m = map(int, input().split())
    g = [[] for _ in range(n)]
    for _ in range(m):
        a, b = map(lambda x: int(x) - 1, input().split())
        g[a].append(b)
        g[b].append(a)
    max_val = 10 ** 9 + 7
    dist = [max_val for _ in range(n)]
    prev = [-1 for _ in range(n)]
    dist[0] = 0
    q = deque([0])
    cnt = 0
    while q:
        now = q.pop()
        for next in g[now]:
            if prev[next] < 0 or dist[now] + 1 < dist[next]:
                if prev[next] < 0:
                    q.append(next)
                    cnt += 1
                else:
                    q.appendleft(next)
                prev[next] = now + 1
                dist[next] = dist[now] + 1
    if cnt == n:
        print("Yes")
        for i in range(1, n):
            print(prev[i])
    else:
        print("No")


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
import networkx as nx

N, M = map(int, input().split())
G = nx.Graph()

for i in range(N):
    G.add_node(i+1)

for i in range(M):
    a,b = map(int, input().split())
    G.add_edge(a,b)
    
G2 = nx.to_scipy_sparse_matrix(G, nodelist=None, dtype=None, weight='weight', format='csr')
d,p = dijkstra(G2,indices = 0, return_predecessors=True)

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

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int,input().split())
tree=[[] for _ in range(n+1)]
ans=[0]*n 
for _ in range(m):
    a,b=map(int,input().split())
    tree[a].append(b)
    tree[b].append(a)
    
checked=[False]*(n+1)
checked[1]=True
stack=[1]
while stack:
    p=stack.pop()
    for i in tree[p]:
        if checked[i]:
            continue
        ans[i-1]=p
        checked[i]=True
        stack=[i]+stack

print('Yes')
for i in ans[1:]:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys

# sys.stdout.write(str(n)+"\n")

INF = 1000000
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
parent = [-1 for i in range(n)]
for i in range(m):
	a, b = map(int, input().split())
	a -= 1
	b -= 1
	graph[a].append(b)
	graph[b].append(a)

q = [0]
# dist = [INF for i in range(n)]
# dist[0] = 0
used = [False for i in range(n)]
parent = [-1 for i in range(n)]
used[0] = True
while len(q) > 0:
	# print("q", q)
	next_ = q.pop(0)
	# used[next_] = 2
	for child in graph[next_]:
		if not used[child]:
			used[child] = True
			q.append(child)
			parent[child] = next_
			# dist[child]
	# print("parent", parent)
	# print("used", used)
	# print()

# connect = True
# for i in range(1, n):
# 	if parent[i] == -1:
# 		connect = False
# 		break

if sum(used) != n: # connect:
	print("No")
else:
	print("Yes")
	for i in range(1, n):
		sys.stdout.write(str(parent[i] + 1)+"\n")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N,M = map(int,input().split())
C = [[] for _ in range(N+1)]
for _ in range(M):
    tmp = list(map(int,input().split()))
    C[tmp[0]].append(tmp[1])
    C[tmp[1]].append(tmp[0])
d = [1000000000]*(N+1)
d[1] = 0
visited = [False]*(N+1)
q = deque()
q.append(1)

while q:
    node = q.popleft()
    visited[node] = True
    for adj in C[node]:
        if visited[adj] == False:
            d[adj] = min(d[node]+1,d[adj])
            q.append(adj)

sirube = [0]*(N+1)
for i in range(2,N+1):
    min_d = 10000000000
    for adj in C[i]:
        if d[adj] < min_d:
            sirube[i] = adj
            min_d = d[adj]


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

Submission status: Time Limit Exceeded

Solution code:
N, M = list(map(int,input().split()))
G = [[] for _ in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    G[a - 1].append(b - 1)
    G[b - 1].append(a - 1)
    
ans = [-1 for _ in range(N)]
ans[0] = 1

stack = [0]

while stack:
    j = stack.pop(0)
    for i in G[j]:
        if ans[i] == -1:
            ans[i] = j
            stack.append(i)
            
for i in range(1, N):
    if ans[i] == -1:
        print("No")
        break
        
else:
    print("Yes")            
    for i in range(1, N):
        print(ans[i] + 1)

Submission status: Time Limit Exceeded

Solution code:
n,m = (int(x) for x in input().split())

E = [[] for i in range(n+1)]

for i in range(m):
    a,b = (int(x) for x in input().split())
    E[a].append(b)
    E[b].append(a)

#print(E)   

flag = [False]*(n+1)
vs = [1]
flag[1] = True
res = [0]*(n+1)

while(vs):
    this_v = vs[0]
    for i in E[this_v]:
        if flag[i]:
            continue
        else:
            res[i] = this_v
            flag[i] = True
            vs.append(i)
    vs.pop(0)
            
print("Yes")
for i in res[2:]:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int,input().split())
g = [[] for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)
from collections import deque
d = deque([[0,0]]) # 左は今考えてる部屋、右は前の部屋
ans = [-1 for i in range(n)]
while d:
    u,v = d.popleft()
    if ans[u] == -1:
        ans[u] = v
    for j in g[u]:
        if ans[j] == -1:
            d.append([j,u])
        else:
            continue
print('Yes')
for i in range(1,n):
    print(ans[i]+1)