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 deque
import math
N,M=map(int,input().split())
"""
BFSする。探索される側をメモ。
"""
dist = [-1 for i in range(N)]
graph = [[] for i in range(N)]
for i in range(M):
  A,B=map(int,input().split())
  graph[A-1].append(B)
  graph[B-1].append(A)
  
#print(dist, graph)

# init
ans = [0]*N
dist = [-1]*N
nodes_ = deque()
q = deque()
q.append(1)
change = False
while len(q)>0:
  #print(q,dist)
  node = q.popleft()
  if node is None:
    break
  elif -1 not in dist:
    break
  if node not in dist:
    dist[node-1] = 0
    if node != 1:
      ans[node-1] = nodes_.popleft()
    #for i in graph[node-1]:
    #  if i not in dist:
    q_ = q
    add = 0
    for j in graph[node-1]:
      if dist[j-1] == -1 and (j not in q):
        q.append(j)
        add+=1
    judge_index = add
    # q.extend(graph[node-1])
  for i in range(add):
    nodes_.append(node)
print("Yes")
print("\n".join(list(map(str,ans[1:]))))

Submission status: Time Limit Exceeded

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

table[0] = 1

miti_a = [[] for i in range(N)]
miti_b = [[] for i in range(N)]



for i in range(M):
    miti_a[a[i]].append(i)
    miti_b[b[i]].append(i)


#start
q = [0]
cnt = 1

while(q):
    if cnt==N:
        break
    
    
    x = q[0]
    
    for i in range(len(miti_a[x])):
        if cnt==N:
            break
    
        m = miti_a[x][i]
        if table[b[m]]==0:
            table[b[m]]=1
            ans[b[m]]=a[m]+1
            q.append(b[m])
            cnt += 1
            
    for i in range(len(miti_b[x])):
        
        if cnt==N:
            break
        m = miti_b[x][i]

        if b[m] == x and table[a[m]]==0:
            table[a[m]]=1
            ans[a[m]]=b[m]+1
            q.append(a[m])      
            cnt +=1
    
    q.pop(0)

if sum(table)==N:
    print("Yes")
    for i in range(1,N):
        print(ans[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import queue

n,m = map(int, input().split())
routs = [[] for i in range(n + 1)]
for i in range(m):
    a, b = map(int,input().split())
    routs[a].append(b)
    routs[b].append(a)

parent = [-1] * (n-1)
visit = ["yet"]*(n)
visit[0] = "done"
q = queue.Queue()
q.put(1)
while -1 in parent:
    temp = q.get()
    for i in routs[temp]:
        if visit[i-1] == "yet":
            q.put(i)
            if parent[i-2] == -1:
                parent[i-2] = temp
            visit[i-1] = "done"
print("Yes")
for i in parent:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from scipy.sparse.csgraph import shortest_path
    from scipy.sparse import csr_matrix
    import numpy as np
    n, m = map(int, input().split())
    edge = np.array([input().split() for _ in range(m)], dtype=np.int32).T
    a = csr_matrix(([1] * m, (edge - 1)), shape=(n, n))
    s, p = shortest_path(a, return_predecessors=True,
                         indices=0, directed=False, unweighted=True)
    if min(p[1:]) < -1:
        print("No")
    else:
        print("Yes")
        for i in p[1:]:
            print(i + 1)


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import math
(r, p)=[int(n) for n in input().split()]
route_list=[[0 for j in range(r)] for i in range(r)]
for i in range(p):
  (x, y)=[int(n)-1 for n in input().split()]
  route_list[x][y] = 1
  route_list[y][x] = 1 

node_num = len(route_list)

unsearched_nodes = list(range(node_num))
distance = [math.inf] * node_num
previous_nodes = [-1] * node_num
distance[0] = 0

def initial():
  unsearched_nodes = list(range(node_num))
  distance = [math.inf] * node_num
  previous_nodes = [-1] * node_num
  distance[0] = 0

def get_target_min_index(min_index, distance, unsearched_nodes):
    start = 0
    while True:
        index = distance.index(min_index, start)
        found = index in unsearched_nodes
        if found:
            return index
        else:
            start = index + 1

while(len(unsearched_nodes) != 0):
    posible_min_distance = math.inf
    for node_index in unsearched_nodes:
        if posible_min_distance > distance[node_index]: 
            posible_min_distance = distance[node_index]
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes)
    unsearched_nodes.remove(target_min_index)

    target_edge = route_list[target_min_index]
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis
                previous_nodes[index] =  target_min_index

ans=[-1]*(r-1)
for i in range(1, r):
  initial()
  if ans[i-1] != -1:
    continue
  previous_node = i
  string=""
  while previous_node != -1:
    if previous_node !=0:
        string += str(previous_node + 1) + " "
    else:
        string += str(previous_node + 1)
    previous_node = previous_nodes[previous_node]
  string = string.split()
  for i, v in enumerate(string[:-1]):
    ans[int(v)-2]=string[i+1]

if "No" in ans:
  print("No")
else:
  print("Yes")
  for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
sys.setrecursionlimit(10**7)
def run():
    N, M = map(int, sysread().split())
    to = [[] for _ in range(N+1)]
    AB = list(map(int, read().split()))
    A = AB[::2]
    B = AB[1::2]
    for a,b in zip(A,B):
        to[a].append(b)
        to[b].append(a)

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

    while True:
        try:
            dist, current, prev = heappop(stack)
        except:
            break
        seen[current] = True
        if not done[current]:
            done[current] = True
            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:
N, M = map(int, input().split())

inv = [i for i in range(N-1)]
visited = [1]

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

for i in range(M):
  A, B = map(int, input().split())
  path[A-1].append(B)
  path[B-1].append(A)
nows = [1]
for t in range(N):
  buf = []
  buf2 = []
  for now in nows:
    buf2 = buf2 + path[now-1]
  buf2 = set(buf2)
  buf3 = set(visited)
  buf2 = buf2 - buf3
  for p in buf2:
    buf.append(p)
    visited.append(p)
    inv[p-2]=now
  if len(buf)==0:
    break
  nows = buf
print("Yes")
for i in inv:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int,input().split())
l = [[0 for x in range(2)] for y in range(m)]
for i in range(m):
    l[i] = list(map(int,input().split()))
l2 = [m+1 for x in range(n)]
l2[0] = 1
l3 = [0 for x in range(n)]
key = 1
while (max(l2) == m+1):
    for j in range(m):
        x1 = l[j][0]
        x2 = l[j][1]
        if l2[x1-1] == key:
            l2[x2-1] = min(key+1,l2[x2-1])
            if l2[x2-1] == key+1:
                l3[x2-1] = l[j][0]
        if l2[x2-1] == key:
            l2[x1-1] = min(key+1,l2[x1-1])
            if l2[x1-1] == key+1:
                l3[x1-1] = l[j][1]
    key += 1
print("Yes")
for k in range(n-1):
    print(l3[k+1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, defaultdict
from sys import stdin

input = stdin.readline
def main():
    N, M = map(int, input().split())
    route = defaultdict(list)
    for i in range(M):
        a, b = map(int, input().split())
        route[a-1].append(b-1)
        route[b-1].append(a-1)
    
    arrive_time = [0] + [-1] * (N - 1)
    arrive_route = [0] + [-1] * (N - 1)
    q = deque()
    q.append(0)
    while len(q):
        idx = q.pop()
        for c in route[idx]:
            if arrive_time[c] >= 0 and arrive_time[c] <= arrive_time[idx]+1:
                continue
            arrive_time[c] = arrive_time[idx]+1
            arrive_route[c] = idx
            q.append(c)
    if min(arrive_time) < 0:
        print("No") 
    else:
        print("Yes")
        for r in arrive_route[1:]:
            print(r+1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

print("Yes")
while len(queue) > 0:
    # print(queue)
    e, now = queue.pop(0)
    if reached[e] == 0:
        reached[e] = 1
        guide[e] = now
        # edge[e].remove(now)
        for next in edge[e]:
            if next != 1:
                queue.append((next, e))

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

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

n, m = map(int, input().split())
data = []
row = []
col = []
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    data.append(1)
    row.append(a)
    col.append(b)
    data.append(1)
    row.append(b)
    col.append(a)
graph = csr_matrix((data, (row, col)), shape=(n, n))
_, p = dijkstra(graph, return_predecessors=True, unweighted=True, indices=0, limit=n)
for item in p[1:]:
    if(item < 0):
        print("No")
        exit()
print("Yes")
for item in p[1:]:
    print(item + 1)

Submission status: Time Limit Exceeded

Solution code:
def readinput():
    n,m=list(map(int,input().split()))
    rooms = [
        [[],-1,-1] for _ in range(n)
        ]
    for _ in range(m):
        a,b = list(map(int,input().split()))
        rooms[a-1][0].append(b)
        rooms[b-1][0].append(a)
    return n,m,rooms

def labelNext(target, rooms, nokori, cost):
    oitaList=[]
    idx = list(nokori)
    for ii in idx:
        i = ii-1
        room=rooms[i]
        if (target in room[0]) and (room[1] == -1):
            room[1] = target
            room[2] = cost
            oitaList.append(i+1) # 道しるべをおいた部屋番号のリストにするので+1
    nokori -= set(oitaList)  #　道しるべを置いた部屋番号を削除
    return oitaList

def main(n,m,rooms):
    nokori=set(range(2,n+1))  # 道しるべを置いてない部屋番号の集合 (1を除くすべて)
    target=1
    cost=1
    nextList=labelNext(target,rooms, nokori, cost)
    while(len(nokori)>0):
        cost+=1
        nl=[]
        for n in nextList:
            nl.append(labelNext(n,rooms,nokori,cost))
            if(len(nokori)==0):
                break
        nextList=nl
    labelList=[]
    for room in rooms:
        labelList.append(room[1])   
    labelList.pop(0)     
    return labelList

if __name__=='__main__':
    n,m,rooms=readinput()
    labelList=main(n,m,rooms)
    print('Yes')
    for l in labelList:
        print(l)

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
a=[0]*(m+1)
b=[0]*(m+1)
sign=[0]*(n+1)
s_num=0
if n>m:
  tonari=[[0]*(n+1) for i in range(n+1)]
else:
  tonari=[[0]*(m+1) for i in range(m+1)]
  
num=[0]*(n+1)
for i in range(m):
  a[i],b[i]=map(int,input().split())
  tonari[a[i]][num[a[i]]]=b[i]
  tonari[b[i]][num[b[i]]]=a[i]
  num[a[i]]+=1
  num[b[i]]+=1

if n>m:
  for i in range(n+1):
    tonari[i]=set(tonari[i])
else:
  for i in range(m+1):
    tonari[i]=set(tonari[i])
    
check=[1]
while s_num<n-1:
  check2=[]
  
  for k in check:
    for j in tonari[k]:
      if j!=0 and j!=1 and sign[j]==0:
        sign[j]=k
        s_num+=1
        check2.append(j)
  check=check2

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
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())

next_queue = deque()
#delete_items = deque()
sign = [-1] * n

next_queue.append(1)

while next_queue:
    current_number = next_queue.popleft()
    for i in range(m):
        if A[i] == current_number:
            if sign[B[i] - 1] == -1:
                sign[B[i] - 1] = current_number
                if B[i] != 1:
                    next_queue.append(B[i])
                A[i] = -1
                B[i] = -1
#                delete_items.append(i)
        if B[i] == current_number:
            if sign[A[i] - 1] == -1:
                sign[A[i] - 1] = current_number
                if A[i] != 1:
                    next_queue.append(A[i])
                A[i] = -1
                B[i] = -1
#                delete_items.append(i)
#    m -= len(delete_items)
#    for item in sorted(list(delete_items), reverse=True):
#        print(item)
#        A.pop(item)
#        B.pop(item)
print("Yes")
for i in range(1, n):
    print(sign[i])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
way = [[] for i in range(n + 1)]
ans = [-1 for i in range(n + 1)]
reached = [0 for i in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    way[a].append(b)
    way[b].append(a)
queue = [1]
while len(queue) > 0:
    go = queue.pop(0)
    reached[go] = 1
    for i in range(len(way[go])):
        if (reached[way[go][i]] == 0) and (way[go][i] not in queue):
            queue.append(way[go][i])
            ans[way[go][i]] = go
print('Yes')
for i in range(2, n + 1):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import queue


N,M = map(int, input().split())
A=[]
B=[]
for m in range(M):
  a,b = map(int, input().split())
  A.append(a)
  B.append(b)

dic = {}

for a,b in zip(A,B):
  if not a in dic:
    dic[a] = []
  if not b in dic:
    dic[b] = []

  dic[a].append(b)
  dic[b].append(a)

visited = [0] * N

q = queue.Queue()
visited[0] = 1
n_tot = 1
# print(dic)
q.put(1)
while n_tot < N:
  root = q.get()
  nodes = dic[root]
  for node in nodes:
    if visited[node-1] == 0:
      visited[node-1] = root
      n_tot += 1
#     print("q.queue,root,visited",q.queue,root,visited)
    q.put(node)

print('Yes')
for v in range(1,len(visited)):
  print(visited[v])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N, M = map(int, input().split())
R = [list(map(int, input().split())) for i in range(M)]

F = [1] * N
F[0] = 0
O = [0] * N

Us = [1]
for i in range(N):
    NUs = []
    for j in R:
        if F[j[1] - 1] or F[j[0] - 1]:
            for U in Us:
                if j[0] == U and F[j[1] - 1] == 1:
                    F[j[1] - 1] = 0
                    O[j[1] - 1] = U
                    NUs.append(j[1])
                if j[1] == U and F[j[0] - 1] == 1:
                    F[j[0] - 1] = 0
                    O[j[0] - 1] = U
                    NUs.append(j[0])
    Us = NUs

if np.prod(F):
    print('No')
else:
    print('Yes')
    for i in O[1:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int, input().split())
AB=[list(map(int, input().split())) for _ in range(M)]
que=[1]
tmp=0
tmp_before=0
ls=[0]*(N+1)

while len(que)>0:
	tmp=que.pop(0)
	for i in range(M):
		for h in range(2):
			if AB[i][h]==tmp and ls[AB[i][1-h]]==0:
				que.append(AB[i][1-h])
				ls[AB[i][1-h]]=tmp
				tmp_before=tmp


if all(ls[i]>=1 for i in range(2,N+1)):
	print("Yes")
	for i in range(2,N+1):
		print(ls[i])

else:
	print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
keys = [0] * n
dic = {i: [] for i in range(n)}
for _ in range(m):
    a, b = map(int, input().split())
    dic[a - 1].append(b - 1)
    dic[b - 1].append(a - 1)

for i in dic[0]:
    q.append(i)
    keys[i] = 1
while len(q) > 0:
    next = q.popleft()
    for i in dic[next]:
        if i == 0:
            continue
        if keys[i]:
            continue
        if i not in q:
            q.append(i)
            keys[i] = next + 1
print('Yes')
print(*keys[1:], sep='\n')

Submission status: Time Limit Exceeded

Solution code:
#from pprint import pprint
#from collections import defaultdict
#from collections import Counter
#from copy import deepcopy
#from itertools
#import sys 
#sys.setrecursionlimit(N) #N回まで再起を許可する。

# = map(int,input().split())

# = list(map(int,input().split()))

# = [list(map(int,input().split())) for _ in range(XXXX)]

from collections import deque






n,m = map(int,input().split())

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

ab_count = {key:[] for key in range(1,n+1)}

for i in range(m):
    ab_count[ab_list[i][0]].append(ab_list[i][1])
    ab_count[ab_list[i][1]].append(ab_list[i][0])


#print(ab_count)

que = deque()

#始点は1、階層は0からスタート
que.append([1,0])

checked_dict = {key:[] for key in range(1,n+1)}
temp_dict = {key:[] for key in range(1,n+1)}
where = 0

while que:
    x_pop = que.popleft()
    x = x_pop[0]
    if where != x_pop[1]:
        #階層が代わったから、temp_dictをchecked_dictへ反映させる処理
        for k in range(1,n+1):
            if len(checked_dict[k]) == 0:
                checked_dict[k] = temp_dict[k]
            elif set(checked_dict[k]) & set(temp_dict[k]) != set():
                checked_dict[k] = list(set(checked_dict[k]) & set(temp_dict[k]))

    
    where = x_pop[1]

    for j in ab_count[x]:
        if len(checked_dict[j]) == 0:
            #OK,temp_dictに入れて、queに入れる。
            temp_dict[j].append(x)
            que.append([j,where+1])
        else:
            continue

    

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq

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

g = [[] for _ 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)#番号を修正。0スタートに。
#print(g)

INF = float('inf')
reach = [INF for _ in range(N)] #0からの距離を記録。INF未到達。
reach[0] = 0
par = [-1 for _ in range(N)] #親の位置を記録

Q =[]
heapq.heappush(Q, 0)

while Q:
  v = heapq.heappop(Q)
  for i in range(len(g[v])): #点vから行ける点をすべて探索
    u = g[v][i] #今探索している点
    if u == 0: #始点の場合はスルー
      continue
    if reach[v] + 1 >= reach[u]: #vから来たほうが遠い場合には何もしない。
      continue
    reach[u] = reach[v] + 1 #探索中の点の到達を記録。
    par[u] = v
    heapq.heappush(Q, u)

#print(reach,par)
if INF not in reach[1:]:
  print("Yes")
  for i in range(1,N):
    ans = par[i]+1
    print(ans)
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
r=[[] for x in range(n)]
for c in range(m):
    a,b=map(int,input().split())
    r[a-1].append(b-1)
    r[b-1].append(a-1)
s=[-1]*n
u=[0]
v=[]
for c in range(10**5):
    for d in u:
        for e in r[d]:
            if s[e]==-1:
                s[e]=d
                v.append(e)
    u=v
print('Yes')
for c in range(n-1):
    print(s[c+1]+1)

Submission status: Time Limit Exceeded

Solution code:
import queue

n, m = map(int, input().split())

a = []
b = []

for i in range(m):
	s, t = map(int, input().split())
	a.append(s-1)
	b.append(t-1)

#各部屋から行ける部屋
c = [[] for i in range(n)]

for i in range(m):
	c[a[i]].append(b[i])
	c[b[i]].append(a[i])

q = queue.Queue()
q.put(0)
f = []

#部屋1からの距離
d = [10**6]*n
d[0] = 0

while not q.empty():
	x = q.get()
	if not(x in f):
		for i in c[x]:
			if not(i in f):
				q.put(i)
			d[i] = min(d[i], d[x]+1)
		f.append(x)

print('Yes')
for i in range(1,n):
	m = 10**6
	ans = 0
	for j in c[i]:
		if d[j]<m:
			m = d[j]
			ans = j+1
	print(ans)

Submission status: Time Limit Exceeded

Solution code:

n,m=map(int, input().split())

g=[[] for i in range(n)]
cost = [[float("inf") for i in range(n)] for i in range(n)] 

for i in range(m):
    ai,bi=map(int, input().split())
    g[ai-1].append(bi-1)
    g[bi-1].append(ai-1)
    cost[ai-1][bi-1] = 1
    cost[bi-1][ai-1] = 1
    
seen=[False]*n
    
def dfs(g,v):
    seen[v]=True    
    for nv in g[v]:
        if seen[v]:
            continue
        dfs(g,nv)

def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    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 j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d

################################
        
icnt=0
for v in range(n):
    if seen[v]:
        continue
    dfs(g,v)
    icnt+=1
    
if icnt!=n:
    print("No")
else:
    print("Yes")

    q=dijkstra(0,n,m,cost)
    r=[0]*n
    for i in range(1,len(q)):
        qmin=10**10
        for j in g[i]:
            if qmin>q[j]:
                qmin=q[j]
                r[i]=j
#            print("1:",g[i],j,q[j],qmin)
        print(r[i]+1)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
A, B = [], []
for i in range(M):
    a, b = map(int, input().split())
    A.append(a)
    B.append(b)

class Rs():
    def __init__(self):
        self.Rs = []

    def append(self, R):
        self.Rs.append(R)

    def search(self):
        self.searched = [0] * len(self.Rs)

        w = 1
        count = 1
        new_nodes, count = self._search(1, w, count)
        while count < N:
            w += 1
            _new_nodes = []
            for num in new_nodes:
                _new_node, count = self._search(num, w, count)
                _new_nodes.extend(_new_node)
            new_nodes = _new_nodes

        return [ self.Rs[i].fastest_room for i in range(1,len(self.Rs)) ]

    def _search(self, num, w, count):
        r = self.Rs[num-1]
        cons = r.connection
        new_nodes = []
        cons -= r.searched_from

        for con in cons:
            weight = self.Rs[con-1].weight
            if weight is None:
                self.Rs[con-1].weight = w
                self.Rs[con-1].fastest_room = num
                self.Rs[con-1].searched_from.add(num)
                new_nodes.append(con)
                count += 1
            else:
                continue
        return new_nodes, count

class R():
    def __init__(self, num, connection):
        self.num        = num
        self.connection = connection
        self.weight     = None
        self.searched_from = set([])
        self.fastest_room = None

r = Rs()
for i in range(N):
    cons = []
    for j, (a, b) in enumerate(zip(A, B)):
        if a == (i+1):
            cons.append(B[j])
        elif b == (i+1):
            cons.append(A[j])
    r.append(R(i+1, set(cons)))

l = r.search()
print("Yes")
for room in l:
    print(room)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra


n,w = map(int,input().split()) #n:頂点数　w:辺の数



cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(w):
    x,y = map(int,input().split())
    cost[x-1][y-1] = 1
    cost[y-1][x-1] = 1

edge=np.array(cost).T
distance_mat, processors = dijkstra(edge, directed = False, indices = [0, 1], return_predecessors = True)

p=processors[0]
p=p[1:]

if(-9999 in p):
    print("No")
    exit()
else:
    print("Yes")

for i in p:
    print(i+1)

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()))
    A = AB[::2]
    B = AB[1::2]
    for a,b in zip(A,B):
        to[a].append(b)
        to[b].append(a)

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

    while True:
        try:
            dist, current, prev = heappop(stack)
        except:
            break
        seen[current] = True
        if not done[current]:
            done[current] = True
            mark[current] = str(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 queue

n, m = map(int, input().split())

a, b = [], []
result = [-1] * n
way = dict()
result[0] = 0

for i in range(m):
    aa, bb = map(int, input().split())
    # aa, bb = 1, 2
    a.append(aa)
    b.append(bb)
    way[aa - 1] = way.get(aa - 1, []) + [bb - 1]
    way[bb - 1] = way.get(bb - 1, []) + [aa - 1]

visited = False
waits = queue.Queue()
waits.put(0)

while not waits.empty():
    current = waits.get()
    # print("current", current)
    # print(way.get(current, []))
    for w in way.get(current, []):
        if result[w] == -1:
            result[w] = current + 1
            waits.put(w)
            # print("Pushed", w)

if -1 in result:
    print("No")
else:
    print("Yes")
    for i in result[1:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
roots = [list(map(int, input().split())) for _ in range(M)]

nvisit = list(range(2, N + 1))
visit = [None for _ in range(N + 1)]
min_visit = [1]

while nvisit != []:
  next_visit = []
  for v in min_visit:
    for root in roots:
      if v in root:
        i = 1 - root.index(v)
        if root[i] in nvisit:
          nvisit.remove(root[i])
          visit[root[i]] = v
          next_visit.append(root[i])
  
  min_visit = next_visit

print("Yes")
for s in visit[2:]:
  print(s)

Submission status: Time Limit Exceeded

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

N, M = map(int, readline().split())
ans = []
append_ans = ans.append
graph = [[] for _ in range(N+1)]

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

root = 1
q = [root]
append_q = q.append
checked = [0] * (N + 1)
#checked[root] = 1
order = []
append_order = order.append
parent = [-1 for _ in range(N+1)]

while q:
    x = q.pop(0)
    if checked[x]:
        continue
    checked[x] = 1
    for y in graph[x]:
        if checked[y]:
            continue
        if parent[y] != -1:
            continue
        parent[y] = x
        append_ans(x)
        append_order(y-2)
        #checked[y] = 1
        append_q(y)

if len(order) != N - 1:
    print('No')
else:
    print('Yes')
    for i in range(len(order)):
        j = order.index(i)
        print(ans[j])

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

def bfs(AB,N):
    S = [None for _ in range(N+1)]
    #S[i]:部屋iにつけるべきサイン
    q = Queue()
    q.put(1)

    while not q.empty():
        p = q.get()
        for i in range(1,N+1):
            if (p,i) in AB and S[i] == None:
                q.put(i)
                S[i] = p

    can = True
    for i in range(2,N+1):
        if S[i] == None:
            can = False

    if can:
        return S[2:]
    else:
        return -1

def main():
    N,M = map(int,input().split())
    AB = [tuple(map(int,input().split())) for _ in range(M)]

    AB_ = set(AB)
    for i in range(M):
        AB_.add((AB[i][1],AB[i][0]))
    AB = AB_

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse.csgraph import breadth_first_tree
from scipy.sparse import csr_matrix
N, M = map(int,input().split())
l = [[0]*(N) for _ in range(N)]
for i in range(M):
    A, B = map(int,input().split())
    l[A-1][B-1] = 1
    l[B-1][A-1] = 1

csr = csr_matrix(l)
Tcsr = breadth_first_tree(csr, 0, False)
ans = np.dot(Tcsr.toarray().T.astype(int), np.arange(N)+1)
if int(np.sum(Tcsr)) != N-1:
    print("No")
else:
    print("Yes")
    for i in range(1, N):
        print(ans[i])