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: Runtime Error

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()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    check=[False for _ in range(n)]
    queue=[n for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    last_ind=1
    while last_ind<n:
        #全探索が終わらない場合
        if queue[now]==n:
            return []
        if check[queue[now]]:
            now+=1
            continue
        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if check[edge]:
                continue

            queue[last_ind]=edge
            last_ind+=1
            #check[edge]=True
            
            ans[edge]=queue[now]
        check[queue[now]]=True
        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))

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

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

Submission status: Runtime Error

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()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    check=[False for _ in range(n)]
    queue=[n for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    last_ind=1
    while last_ind<n:
        print(now)
        print(queue)
        print(check)
        print()
        #全探索が終わらない場合
        if queue[now]==n:
            return []
        if check[queue[now]]:
            now+=1
            continue
        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if check[edge]:
                continue

            queue[last_ind]=edge
            last_ind+=1
            #check[edge]=True
            
            ans[edge]=queue[now]
        check[queue[now]]=True
        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))

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

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

Submission status: Runtime Error

Solution code:
# import numpy as np
# import copy
import queue


q = queue.Queue()

n, m = map(int, input().split())
l = [[0 for _ in range(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


# l = np.array(l)
# lc = copy.deepcopy(l)
li = [-1 for _ in range(n)]

def search(x):
    if sum(lc[x]) == 0:
        q.queue = False
        return
    
#     ind_lis = np.where(lc[x] == 1)[0]
#     ind_lis = [e for e in ind_lis if li[e] == -1]
#     print(li)
#     print(lc[x])
    for i,e in enumerate(l[x]):
#         print(i,e)
        if li[i] != -1 or e == 0:
            continue
        li[i] = x
#         print('q', i+1)
        q.put(i)
x = 0
search(x)
while q.queue:
    search(q.get())

if li[1:].count(-1) == 0:
    print('Yes')
    for e in li[1:]:
        print(e+1)
else:
    print('No')

Submission status: Runtime Error

Solution code:
import numpy as np
N, M = list(map(int, input().split()))
lis = []
room = np.zeros(N+1)
dep = np.zeros(N+1)
ans = np.zeros(N+1)
for i in range(M):
    a,b=list(map(int, input().split()))
    lis.append((a, b))
    room[a] = room[a]*10 + b
    room[b] = room[b]*10 + a
    
def root(p, c):
  global ans
  global dep
  print(dep)
  if (p == 1 or (c != 1 and (dep[c] > dep[p] or dep[c] == 0))):
    dep[c] = dep[p] + 1
    ans[c] = p
    s = str(room[c])
    for i in range(len(s)-2):
      root(c, int(s[i]))
for i in range(len(lis)):
  if lis[i][0] == 1:
    root(1, lis[i][1])
  elif lis[i][1] == 1:
    root(1, lis[i][0])
flag = 1
for i in range(2, N+1):
  if ans[i] == 0:
    flag = 0
if flag == 1:
  print("Yes")
  for i in range(2, N+1):
    print(int(ans[i]))
else:
  print("No")

Submission status: Runtime Error

Solution code:
# import numpy as np
import copy
import queue


q = queue.Queue()

n, m = map(int, input().split())
l = [[0 for _ in range(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


l = np.array(l)
lc = copy.deepcopy(l)
li = [-1 for _ in range(n)]

def search(x):
    if sum(lc[x]) == 0:
        q.queue = False
        return
    
#     ind_lis = np.where(lc[x] == 1)[0]
#     ind_lis = [e for e in ind_lis if li[e] == -1]
#     print(li)
#     print(lc[x])
    for i,e in enumerate(lc[x]):
#         print(i,e)
        if li[i] != -1 or e == 0:
            continue
        li[i] = x
#         print('q', i+1)
        q.put(i)
x = 0
search(x)
while q.queue:
    search(q.get())

if li[1:].count(-1) == 0:
    print('Yes')
    for e in li[1:]:
        print(e+1)
else:
    print('No')

Submission status: Runtime Error

Solution code:
from collections import deque
import numpy as np


def main():
    n,m = map(int,input().split())
    arr = np.zeros([n, n])
    for _ in range(m):
        a, b = map(int,input().split())
        arr[a-1][b-1] = 1
        arr[b-1][a-1] = 1
    q = deque()
    q.append(0)
    ans = {i:0 for i in range(1, n)}
    while q:
        now = q.popleft()
        for i in range(n):
            if arr[now][i] == 0:
                continue
            if i == 0:
                continue
            if ans[i] == 0:
                ans[i] = now+1
                q.append(i)
        if len(q) == 0:
            break
    print('Yes')
    for i in range(1,n):
        print(ans[i])


if __name__=='__main__':
    main()

Submission status: Runtime Error

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()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    check=[False for _ in range(n)]
    queue=[-1 for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    last_ind=1
    while last_ind<n:
        
        if now>=n:
            return []
        if check[queue[now]]:
            now+=1
            continue
        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if check[edge]:
                continue

            queue[last_ind]=edge
            last_ind+=1
            #check[edge]=True
            
            ans[edge]=queue[now]
        check[queue[now]]=True
        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))

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

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

Submission status: Runtime Error

Solution code:
# list(map(int, input().split()))
# int(input())
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while st > 0:
            next_st = set([])
            for n in st:
                if len(AB[n]) == 0:
                    print('No')
                    exit()
                else:
                    for ab in AB[n]:
                        if lst[ab - 1] == 0:
                            lst[ab - 1] = n
                            next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst
    # try:
    #     ans = serch()
    # except:
    #     print('No')
    #     exit()

    ans = serch()
    if ans = None or 0 in set(ans[1:]):
        print('No')
    else:
        print('Yes')
        [print(i) for i in ans[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
import networkx as nx
import matplotlib.pyplot as plt
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.single_target_shortest_path(g,target=1)

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

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

Submission status: Runtime Error

Solution code:
import queue
N,M = map(int,input().split())
tree = [[] for _ in range(M+1)]
for i in range(M):
    a,b = map(int,input().split())
    tree[a].append([b,a])
    tree[b].append([a,b])

que = queue.Queue()
que.put(1)
result = [[-1,100000] for _ in range(N+1)]
result[1][1] = 0

while(True):
    if que.empty():
        break
    nex = que.get()
    
    for i in tree[nex]:
        if result[i[0]][0] == -1  :
            result[i[0]][0] = nex
            result[i[0]][1] = result[nex][1] +1

            
            que.put(i[0])

for i in range(2,N+1):
    for j in tree[i]:
        if result[j[0]][1] == result[i][1] -1:
            result[i][0] = j[0] 
result = result[2:]
if result.count(-1) !=0:
    print("No")
else :
    print("Yes")
    for i in result:
        print(i[0])

Submission status: Runtime Error

Solution code:
import numpy as np
N, M = list(map(int, input().split()))
lis = []
room = np.zeros(N+1)
dep = np.zeros(N+1)
ans = np.zeros(N+1)
for i in range(M):
    a,b=list(map(int, input().split()))
    lis.append((a, b))
    room[a] = room[a]*10 + b
    room[b] = room[b]*10 + a
    
def root(p, c):
  global ans
  global dep
  if p == 1:
    ans[c] = p
    dep[c] = dep[p] + 1
    s = str(room[c])
    for i in range(len(s)-2):
      root(c, int(s[i]))
  elif (c != 1 and (dep[c] == 0 or dep[c] > dep[p])):
    ans[c] = p
    dep[c] = dep[p] + 1
    s = str(room[c])
    for i in range(len(s)-2):
      root(c, int(s[i]))
  
for i in range(len(lis)):
  if lis[i][0] == 1:
    root(1, lis[i][1])
  elif lis[i][1] == 1:
    root(1, lis[i][0])
flag = 1
for i in range(2, N+1):
  if ans[i] == 0:
    flag = 0
if flag == 1:
  print("Yes")
  for i in range(2, N+1):
    print(int(ans[i]))
else:
  print("No")

Submission status: Runtime Error

Solution code:
# list(map(int, input().split()))
# int(input())
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while st > 0:
            next_st = set([])
            for n in st:
                try:
                    if len(AB[n]) == 0:
                        print('No')
                        exit()
                    else:
                        for ab in AB[n]:
                            if lst[ab - 1] == 0:
                                lst[ab - 1] = n
                                next_st.add(ab)
                except:
                    print('No')
                    exit()
            return serch(next_st, lst)
        else:
            return lst

    ans = serch()
    if 0 in set(ans[1:]):
        print('No')
    else:
        print('Yes')
        [print(i) for i in ans[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
import queue
N,M = map(int,input().split())
tree = [[] for _ in range(M+1)]
for i in range(M):
    a,b = map(int,input().split())
    tree[a].append([b,a])
    tree[b].append([a,b])

que = queue.Queue()
que.put(1)
result = [[-1,100000] for _ in range(N+1)]
result[1][1] = 0

while(True):
    if que.empty():
        break
    nex = que.get()
    
    for i in tree[nex]:
        if result[i[0]][0] == -1  :
            result[i[0]][0] = nex
            result[i[0]][1] = result[nex][1] +1

            
            que.put(i[0])

for i in range(2,N+1):
    for j in tree[i]:
        if result[j[0]][1] == result[i][1] -1:
            result[i][0] = j[0] 
result = result[2:]
if result.count(-1) !=0:
    print("No")
else :
    print("Yes")
    for i in result:
        print([i[0]])

Submission status: Runtime Error

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

paths = [set() for _ in range(M)]
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    paths[a].add(b)
    paths[b].add(a)

rooms = [-1] * N
rooms[0] = 0
marks = [-1] * (N-1)
key_rooms = [[0]]
for step in range(1, N):
    next_key_rooms = set()
    for key_room in key_rooms[-1]:
        for else_room in paths[key_room]:
            if rooms[else_room] == -1:
                rooms[else_room] = step
                next_key_rooms.add(else_room)
                marks[else_room-1] = key_room
    key_rooms.append(next_key_rooms)

print('Yes')
for i in marks:
    print(i+1)

Submission status: Runtime Error

Solution code:
import queue
N,M = map(int,input().split())
tree = [[] for _ in range(M+1)]
for i in range(M):
    a,b = map(int,input().split())
    tree[a].append([b,a])
    tree[b].append([a,b])

que = queue.Queue()
que.put(1)
result = [[-1,100000] for _ in range(N+1)]
result[1][1] = 0

while(True):
    if que.empty():
        break
    nex = que.get()
    
    for i in tree[nex]:
        if result[i[0]][0] == -1  :
            result[i[0]][0] = nex
            result[i[0]][1] = result[nex][1] +1

            
            que.put(i[0])
print(*result)

for i in range(2,N+1):
    for j in tree[i]:
        if result[j[0]][1] == result[i][1] -1:
            result[i][0] = j[0] 
result = result[2:]
if result.count(-1) !=0:
    print("No")
else :
    print("Yes")
    for i in result:
        print([i[0]])

Submission status: Runtime Error

Solution code:
from collections import deque

def main():
    n,m = map(int,input().split())
    arr = [[] for i in range(n)]
    for _ in range(m):
        a,b = map(int,input().split())
        arr[a-1].append(b-1)
        arr[b-1].append(a-1)
    q = deque()
    q.append(0)
    ans = [-1] * n
    ans[0] = 0
    while q:
        now = q.popleft()
        for i in ab[now]:
            if ans[i] == -1:
                ans[i] = now+1
                q.append(i)
        if len(q) == 0:
            break
    print('Yes')
    for i in range(1,n):
        print(ans[i])



if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
n,m = map(int, input().split())

routes = []
for i in range(m):
    route = list(map(int, input().split()))
    routes.append(route)

for i in range(m):
    routes[i] = routes[i] - np.ones(2) #道の番号をずらす

rooms = np.zeros(n) # 行ってない部屋は0、行った部屋は1
marks = np.zeros(n) # 部屋におく道標
roomsrate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1
marks[0] = 1

for i in range roomsrate:
    newrate = []
    for j in range roomsrate[i]: # i回目に行ける部屋を調べる
        for k in range(m):
            a = int(routes[k][0])
            b = int(routes[k][1]) 
            if (j == a or j == b):
                if (int(rooms[b]) == 0):
                    rooms[b] = 1
                    marks[b] = a
                    newrate.append(b)
                elif (int(rooms[a]) == 0):
                    rooms[a] = 1
                    marks[a] = b
                    newrate.append(a)
    roomsrate.append(newrate)
    if(newrate == [])
    break


if(np.all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

Submission status: Runtime Error

Solution code:
# list(map(int, input().split()))
# int(input())
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while len(st) > 0:
            next_st = set([])
            for n in st:
                if len(AB[n]) == 0:
                    print('No')
                    exit()
                else:
                    for ab in AB[n]:
                        if lst[ab - 1] == 0:
                            lst[ab - 1] = n
                            next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst

    ans = serch()
    if 0 in set(ans[1:]):
        print('No')
    else:
        print('Yes')
        [print(i) for i in ans[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
A=[list(map(int,input().split())) for i in range(M)]
graph=[[]for i in range(N+1)]
for i in range(N):
    u,v=A[i]
    graph[u].append(v)
    graph[v].append(u)

stack=deque([1])
visited=[-1 for i in range(N+1)]
visited2=[-1 for i in range(N+1)]
visited[1]=0
while stack:
    x=stack.popleft()
    for i in graph[x]:
        if visited[i]==-1:
            visited[i]=visited[x]+1
            visited2[i]=x
            stack.appendleft(i)
print('Yes')
print(*visited2[2:],sep='\n')

Submission status: Runtime Error

Solution code:
# list(map(int, input().split()))
# int(input())
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while st:
            next_st = set([])
            for n in st:
                if len(AB[n]) == 0:
                    print('No')
                    exit()
                else:
                    for ab in AB[n]:
                        if lst[ab - 1] == 0:
                            lst[ab - 1] = n
                            next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst

    ans = serch()
    if 0 in set(ans[1:]):
        print('No')
    else:
        print('Yes')
        [print(i) for i in ans[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
from collections import deque
import numpy as np

def main():
    n,m = map(int,input().split())
    arr = np.zeros([n,n])
    for _ in range(m):
        a, b = map(int,input().split())
        arr[a-1][b-1] = 1
        arr[b-1][a-1] = 1
    q = deque()
    q.append(0)
    path = {i:0 for i in range(2, n+1)}
    while q:
        pos = q.popleft()
        for i in range(1, n):
            if arr[pos][i] == 1:
                q.append(i)
                if path[i+1] == 0:
                    path[i+1] = pos + 1
        if len(q) == 0:
            break
        flag = True
        for i in path:
            if path[i] == 0:
                flag = False
        if flag:
            break
    print('Yes')
    for i in path:
        print(path[i])

if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:

import numpy as np

def resolve():
  N, M = map(int, input().split(" "))
  rooms = [None] * N

  def search_and_mark(recent_rooms, ab, depth):
    # if None not in rooms:
    if len(ab) == 0:
      return rooms

    if depth >= N:
      return []

    tmp_rooms = []
    for r in recent_rooms:
      tmp = ab[np.any(ab == r, axis=1)]
      target = tmp[tmp != r]
      tmp_rooms.extend(target)

      tmp = np.all(ab != r, axis=1)
      ab = ab[tmp]
      
      for t in target:
        if rooms[t] == None:
          rooms[t] = r

    recent_rooms = list(set(tmp_rooms))
    return search_and_mark(recent_rooms, ab, depth+1)

  AB = []
  for m in range(M):
    AB.append([int(x) - 1 for x in input().split(" ")])

  AB = np.array(AB)
  result = search_and_mark([0], AB, 0)

  print("Yes")
  for r in result[1:]:
    print(r + 1)

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
from collections import deque
N,M = map(int,input().split())

G = [[] for i in range(M)]
for i in range(M):
  x,y = map(int,input().split())
  G[x-1].append(y-1)
  G[y-1].append(x-1)

dist = [-1]*N #全頂点を未訪問に初期化(-1)で未訪問
que = deque([0])   #初期条件 (頂点 0 を初期ノードとする) 
dist[0] = 0 #0を訪問済み

#BFS 開始 (キューが空になるまで探索を行う)
while que:
    v = que.popleft() #キューから先頭要素を取る
    d = dist[v]
    #v から辿れる頂点をすべて調べる
    for w in G[v]:
        if dist[w] > -1:#探索済みの頂点は無視
            continue
        dist[w] = d + 1 #新たな頂点wについて距離情報を更新してキューに追加する
        que.append(w)
# 結果出力 (各頂点の頂点 0 からの距離を見る)
print("Yes")
for i in range(N-1):
  print(dist[i+1])

Submission status: Runtime Error

Solution code:
S = input()
N = int(S.split()[0])
M = int(S.split()[2])
P = []
for i in range(M):
    P.append(input().split())
Q = [0]*(N+1)
Q[0] = 1
Q[1] = 1
fin = [1]
done = []
T = True
while 0 in Q:
    for i in fin:
        if i not in done:
            for j in range(M):
                x0 = int(P[j][0])
                x1 = int(P[j][1])
                if x0 == i and Q[x1] == 0:
                    Q[x1] = i
                    if x1 not in fin:
                        fin.append(x1)
                    P[j][0] = 0
                    P[j][1] = 0
                if x1 == i and Q[x0] == 0:
                    Q[x0] = i
                    if x0 not in fin:
                        fin.append(x0)
                    P[j][0] = 0
                    P[j][1] = 0
            done.append(i)
        if 0 not in Q:
            break
    if fin == done:
        T = False
        break
if T:
    print('Yes')
    for i in range(2, N+1):
        print(Q[i])
else:
    print('No')

Submission status: Runtime Error

Solution code:
from collections import deque
N,M = map(int,input().split())

G = [[] for i in range(M)]
for i in range(M):
  x,y = map(int,input().split())
  G[x-1].append(y-1)
  G[y-1].append(x-1)

dist = [-1]*N #全頂点を未訪問に初期化(-1)で未訪問
que = deque([0])   #初期条件 (頂点 0 を初期ノードとする) 
dist[0] = 0 #0を訪問済み

#BFS 開始 (キューが空になるまで探索を行う)
while que:
    v = que.popleft() #キューから先頭要素を取る
    d = dist[v]
    #v から辿れる頂点をすべて調べる
    for w in G[v]:
        if dist[w] > -1:#探索済みの頂点は無視
            continue
        dist[w] = d + 1 #新たな頂点wについて距離情報を更新してキューに追加する
        que.append(w)
# 結果出力 (各頂点の頂点 0 からの距離を見る)
for i in range(N-1):
  print("Yes")
  print(dist[i+1])

Submission status: Runtime Error

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
A=[list(map(int,input().split())) for i in range(M)]
graph=[[]for i in range(N+1)]
for i in range(N):
    u,v=A[i]
    graph[u].append(v)
    graph[v].append(u)

stack=deque([1])
visited=[-1 for i in range(N+1)]
visited2=[-1 for i in range(N+1)]
visited[1]=0
while stack:
    x=stack.popleft()
    for i in graph[x]:
        if visited[i]==-1:
            visited[i]=visited[x]+1
            visited2[i]=x
            stack.append(i)
print('Yes')
print(*visited2[2:],sep='\n')

Submission status: Runtime Error

Solution code:
n,m=map(int,input().split())
graph=[[] for i in range(n)]
sirusi=[0]*n
for i in range(m):
    a,b=map(int,input().split())
    a-=1;b-=1
    graph[a].append(b)
    graph[b].append(a)
D=deque([0])
visited=[False]*n
visited[0]=True
while D:
    v=D.popleft()
    for i in graph[v]:
        if visited[i]:continue
        visited[i]=True
        sirusi[i]=v
        D.append(i)
print("Yes")
for i in range(1,n):
    print(sirusi[i]+1)

Submission status: Runtime Error

Solution code:
# D

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import breadth_first_order

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

row = ABs.T[0]
col = ABs.T[1]
data = [1] * (M)

csr = csr_matrix((data, (row, col)), shape=(N, N))
_, proc = breadth_first_order(csr, 0, directed=False)

if -9999 in proc[1:]:
  print('No')
else:
  print('Yes')
  print('\n'.join((proc[1:]+1).astype('str')))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)
def calc(path, dist):
    for r in roads[path]:
        temp = distances[int(r)]
        if temp == 0 or dist < temp:
            distances[int(r)] = dist
            guides[int(r)] = path
            calc(r, dist + 1)


n, m = map(int, input().split())
roads = {}
for i in range(m):
    a, b = input().split()
    if b != "1":
        if a in roads:
            roads[a].append(b)
        else:
            roads[a] = [b]
    if a != "1":
        if b in roads:
            roads[b].append(a)
        else:
            roads[b] = [a]

distances = [0] * (n + 1)
guides = [0] * (n + 1)

calc("1", 1)

distances = distances[2:]
guides = guides[2:]

if 0 in distances:
    print("No")
else:
    print("Yes")
    for guide in guides:
        print(guide)

Submission status: Runtime Error

Solution code:

import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read 
inp = sys.stdin.buffer.readline
def inpS(): return inp().rstrip().decode()
readlines = sys.stdin.buffer.readlines 
MOD = 10**9+7
INF = 1<<60

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

def resolve():
    N, M = map(int, inp().split())
    G = np.zeros((N + 1, N + 1))

    for _ in range(M):
        x, y = map(int, inp().split())
        G[x, y] += 1
        G[y, x] += 1
    csr = csr_matrix(G)
    dist, pred = dijkstra(csgraph=csr, indices=1, return_predecessors=True)

    ans = pred[2:]
    impos = any(ans >= 0)
    if impos:
        print("Yes")
        print(*ans, sep="\n")
    else:
        print("No")

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
# list(map(int, input().split()))
# int(input())
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while st:
            next_st = set([])
            for n in st:
                for ab in AB[n]:
                    if lst[ab - 1] == 0:
                        lst[ab - 1] = n
                        next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst

    ans = serch()
    if 0 in set(ans):
        print('No')
    else:
        print('Yes')
        [print(i) for i in ans[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
import queue
N,M = map(int,input().split())
tree = [[] for _ in range(M+1)]
for i in range(M):
    a,b = map(int,input().split())
    tree[a].append([b,a])
    tree[b].append([a,b])

que = queue.Queue()
que.put(1)
result = [[-1,100000] for _ in range(N+1)]
result[1][1] = 0

while(True):
    if que.empty():
        break
    nex = que.get()
    
    for i in tree[nex]:
        if result[i[0]][0] == -1 or result[i[0]][1] > result[nex][1] :
            result[i[0]][0] = nex
            result[i[0]][1] = result[nex][1] +1

            
            que.put(i[0])


result = result[2:]
if result.count(-1) != 0:
    print("No")
else :
    print("Yes")
    for i in result:
        print(i[0])

Submission status: Runtime Error

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()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    
    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]
    last_ind=1
    while last_ind<n:
        
        if now>=n:
            return []
        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:
                continue
            side_num_arr[edge]-=1
            side_num_arr[queue[now]]-=1
            queue[last_ind]=edge
            last_ind+=1
            
            ans[edge]=queue[now]
        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])

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

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