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

table = [list() for _ in range(n+1)]
ans = [0 for _ in range(n+1)]
hush = {}

for i in range(1, n+1):
    hush[i] = False

for a, b in road:
    table[a].append(b)
    table[b].append(a)

def bfs(i):
    hush[i] = True
    rec = []
    for j in table[i]:
        if hush[j] == False:
            ans[j] = i
            hush[j] = True
            rec.append(j)
    for j in rec:
        bfs(j)

bfs(1)

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

Submission status: Runtime Error

Solution code:
import sys
from collections import deque


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

# BFS
G = [[] for _ in range(N)]
for i in range(N):
    G[A[i] - 1].append(B[i] - 1)
    G[B[i] - 1].append(A[i] - 1)
G = [list(set(x)) for x in G]

q = deque([])
dist = [-1] * N
ans = [-1] * N
dist[0] = 0
q.appendleft(0)
while(len(q) > 0):
    v = q.pop()
    for nv in G[v]:
        if not dist[nv] == -1:
            continue
        dist[nv] = dist[v] + 1
        ans[nv] = v
        q.appendleft(nv)

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

for i, v in enumerate(ans):
    if i == 0:
        print('yes')
        continue
    print(v + 1)

Submission status: Runtime Error

Solution code:
[n,m]=list(map(int,input().split()))
ab=[]
for i in range(m):
    ab.append(list(map(int,input().split())))

chizu=[[] for i in range(n+1)]
ans=[0]*(n+1)
ans[1]=-1

for i in range(m):
    chizu[ab[i][0]].append(ab[i][1])
    chizu[ab[i][1]].append(ab[i][0])

kaisu=[chizu[1]]
for i in chizu[1]:
    ans[i]=1

error=0
j=-1
counter=len(chizu[1])
while True:
    j+=1
    for now in kaisu[j]:#スタートからj+1距離の点たちについて操作
        kari=[]
        for i in chizu[now]:#ある点から隣り合う点決めていく
           if ans[i]==0:#未到達であれば
                ans[i]=now
                kari.append(i)
                counter+=1
        kaisu.append(kari)
    if counter==n-1:
        break

if error==0:
    print("Yes")
    for i in range(2,n+1):
        print(ans[i])
    

elif error==1:
    print("No")

Submission status: Runtime Error

Solution code:
#-------------------------------------------------------------------
import sys
def p(*_a):
  _s=" ".join(map(str,_a))
  #print(_s)
  sys.stderr.write(_s+"\n")
#-------------------------------------------------------------------
n,m = map(int, input().split())		# 5 7 2

A=[0]
B=[0]
G = [ [] for i in range(m+1) ]

for i in range(m):
	a,b = map(int, input().split())		# 5 7 2
	A.append(a)
	B.append(b)
	G[a].append(b)
	G[b].append(a)

#p("G=", G)

#X = [0]*(n+1)
L_MAX = 100100100
X = [ [0,L_MAX] for i in range(n+1) ]

X[1][0] = 1
X[1][1] = 0

from collections import deque

Q = deque()

fm = 1
to = 1
Q.append(1)

while Q:
	fm = Q.popleft()

	g = G[fm]
	for to in g:
		p("fm,g,to,Q=",fm,g,to,Q)
		if (X[to][1] > X[fm][1]+1):
			X[to][0] = fm
			X[to][1] = X[fm][1] + 1
			Q.append(to)
			continue
		
		if (X[to][1]+1 < X[fm][1]):
			X[fm][0] = to
			X[fm][1] = X[to][1] + 1
			Q.append(fm)
			continue


#p("X =",X)
#p("X2=",X[2:])

Y = X[2:]

for a,l in Y:
	if l == L_MAX:
		print("No")
		exit(0)

print("Yes")
for a,l in Y:
	print(a)

p("Y=",Y)

Submission status: Runtime Error

Solution code:
from collections import deque
n, m = map(int, input().split())
li = [list(map(int, input().split())) for _ in range(m)]

ans = [deque([]) for _ in range(m+10)]
ans2 = [[] for _ in range(m+10)]
for i in range(m):
    s = li[i][0]
    t = li[i][1]

    ans[s].append(t)
    ans[t].append(s)

stack = deque([1])
while stack:
    v = stack[0]

    if ans[v]:
        w = ans[v].popleft()
        if True:
            ans2[w].append(v)
        stack.append(w)
    else:
        stack.popleft()

print('Yes')
for i in range(2, m+1):
    print(ans2[i][0])

Submission status: Runtime Error

Solution code:
N,M =  (int(x) for x in input().split())
A = [[0 for j in range(1)] for i in range(M+1)]
ans = [None]*(M)
num = M - 1
nextnum = []
newnextnum = []
for i in range(M):
    a,b =  (int(x) for x in input().split())
    A[a].append(b)
    A[b].append(a)
if(A[1] == [0]):
    print ("No")
else:
    for i in A[1]:
        if i != 0:
            ans[i-1] = 1
            num -= 1
            nextnum.append(i)
    while(num>0):
        for j in range(len(nextnum)):
            for i in A[nextnum[j]]:
                if i != 0 and i != 1 and ans[i-1] == None:
                    ans[i-1] = nextnum[j]
                    num -= 1
                    newnextnum.append(i)
        nextnum = newnextnum
        nextnum = []
    print("Yes")
    for i in range(1,len(ans)):
        print(ans[i])

Submission status: Runtime Error

Solution code:
MAX_INT = 10**6
N, M = map(int, input().split())
room = [set() for _ in range(N+1)]
for i in range(M):
    a, b = map(int, input().split())
    room[a].add(b)
    room[b].add(a)

dis = [MAX_INT] * (N + 1)
sign = [-1] * (N + 1)
dis[1] = 0
def sign_root(n):
    for i in room[n]:
        if dis[n] + 1 < dis[i] and n in room[i]:
            sign[i] = n
            dis[i] = dis[n] + 1
            room[i].remove(n)
            sign_root(i)
sign_root(1)
if MAX_INT in dis[2:]:
    print("No")
else:
    print("Yes")
    for i in sign[2:]:
        print(i)

Submission status: Runtime Error

Solution code:
num = [1]
def func(k):
    for h in lst[k]:
        if ans[h] == 0:
            ans[h] = k
            num[0] += 1
    unused.remove(k)
    new_lst = []
    for hh in  lst[k]:
        if hh in unused:
            new_lst.append(hh)
    for hh in new_lst:
        new_need.append(hh)



a = input().split(" ")
N = eval(a[0])
M = eval(a[1])
lst = [0]
ans = [0]
exist = [1]
unused = []
needed_to = [1]
for i in range(1, N + 1):
    unused.append(i)
for i in range(N):
    lst.append([])
    ans.append(0)
    exist.append(0)
ans[1] = 1
for i in range(M):
    a = input().split(" ")
    a1 = eval(a[0])
    a2 = eval(a[1])
    lst[a1].append(a2)
    lst[a2].append(a1)
    exist[a1] = 1
    exist[a2] = 1
for i in range(1, N + 1):
    lst[i] = list(set(lst[i]))
action = 1
for i in exist:
    if i == 0:
        action = 0
new_need = [1]
if action == 0:
    print("No")
else:
    while num[0] < N:
        needed_to = list(set(new_need))
        new_need = []
        for i in needed_to:
            func(i)
            needed_to.remove(i)
    print("Yes")
    for i in range(2, N + 1):
        print(ans[i])

Submission status: Runtime Error

Solution code:



# print('input >>')
N, M = map(int,(input().split()))
ABs = [map(int,(input().split())) for _ in range(M)]

INF = 10 ** 10
ds = [0] * (N+1)
marks = [0] * (N+1)

nodes = [None] * (N+1)

for AB in ABs:
    A, B = AB
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

    B, A = A, B
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

# print(nodes)

checked = [0] * (N+1) 

def dfs(cur, parent, children):
    # print(parent, children)
    if checked[parent] == 1:
        return
    checked[parent] = 1
    for child in children:
        # print(cur, ds)
        if marks[child] == 0 or ds[child] > cur:
            marks[child] = parent
            ds[child] = cur
            # print(marks)
        # if not checked[child] == 0:
        dfs(cur+1, child, nodes[child])

dfs(0, 1, nodes[1])

# print('-----output-----')
print('Yes')
for mark in marks[2:]:
    print(mark)

"""
7 7
1 2
2 5
5 7
3 1
7 3
6 1
2 4
"""

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import networkx as nx


def main():
    n, m = map(int, input().split())

    g = nx.Graph()
    for _ in range(n):
        a, b = map(int, input().split())
        g.add_edge(a, b)
    path = list(nx.bfs_edges(g, 1))

    if len(path) != n - 1:
        print('No')
        return
    print('Yes')
    for p in path:
        print(p[0])


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
num = [1]
def func(k):
    for h in lst[k]:
        if ans[h] == 0:
            ans[h] = k
            num[0] += 1
    unused.remove(k)
    new_lst = []
    for hh in  lst[k]:
        if hh in unused:
            new_lst.append(hh)
    for hh in new_lst:
        new_need.append(hh)



a = input().split(" ")
N = eval(a[0])
M = eval(a[1])
lst = [0]
ans = [0]
exist = [1]
unused = []
needed_to = [1]
for i in range(1, N + 1):
    unused.append(i)
for i in range(N):
    lst.append([])
    ans.append(0)
    exist.append(0)
ans[1] = 1
for i in range(M):
    a = input().split(" ")
    a1 = eval(a[0])
    a2 = eval(a[1])
    lst[a1].append(a2)
    lst[a2].append(a1)
    exist[a1] = 1
    exist[a2] = 1
for i in range(1, N + 1):
    lst[i] = list(set(lst[i]))
action = 1
for i in exist:
    if i == 0:
        action = 0
new_need = [1]
if action == 0:
    print("No")
else:
    while num[0] < N:
        needed_to = list(set(new_need))
        new_need = []
        for i in needed_to:
            func(i)
            needed_to.remove(i)
    print("Yes")
    for i in range(2, N + 1):
        print(ans[i])

Submission status: Runtime Error

Solution code:
import math
MOD =1000000007


def pow_k(x, n):
    if n == 0:
        return 1

    K = 1
    while n > 1:
        if n % 2 != 0:
            K *= x
        x *= x
        n //= 2
        # print(K,x)
        x%=MOD
    return K * x


n = int(input())

a_b_d = {}
# b_a_d = {}

a_zero_cnt = 0
b_zero_cnt = 0
ab_zero_cnt = 0

for i in range(n):
    a, b = map(int, input().split()) 
    if a==0 and b!=0:
        a_zero_cnt += 1
    elif  a!=0 and b==0:
        b_zero_cnt += 1
    elif a == 0 and b == 0:
        ab_zero_cnt += 1
    else:
        gcd_ab = math.gcd(a,b)
        a = a//gcd_ab
        b = b//gcd_ab
        if a > 0 and b < 0:
            a *= -1
            b *= -1
        elif a < 0 and b < 0:
            a *= -1
            b *=-1
        a_b_d.setdefault((a,b),0)
        a_b_d[(a,b)] += 1


done_list = set()
pair_cnt = []
uniq_cnt = 0
for k,v in a_b_d.items():
    comp_pair1 = (-k[1], k[0])
    comp_pair2 = (k[1], -k[0])
    if k in done_list:
        continue
    if comp_pair1 in a_b_d:
        # print(k, comp_pair)
        done_list.add(comp_pair1)
        pair_cnt.append((v,a_b_d[comp_pair1]))
    elif comp_pair2 in a_b_d:
        # print(k, comp_pair)
        done_list.add(comp_pair2)
        pair_cnt.append((v,a_b_d[comp_pair2]))
    else:
        uniq_cnt += 1


ans = pow_k(2,uniq_cnt) % MOD
for pair in pair_cnt:
    ans *= (pow_k(2,pair[0]) + pow_k(2,pair[1]) -1 )
    ans%=MOD

zero_m = max(pow_k(2,a_zero_cnt) + pow_k(2,b_zero_cnt) -1, 1)
# print(ans)
ans *= zero_m
# ans *= (zero_cnt+1)
ans -= 1
print(ans%MOD)

Submission status: Runtime Error

Solution code:
# coding: utf-8

#Nはノード数、Mはエッジ数
N, M = map(int, input().split())

path_matrix = []
#無向行列の初期化
for n in range(N):
    path_matrix.append([False] * N)
#まず無向グラフを表す行列を作る
for m in range(M):
    line = map(int, input().split())
    paths = [x - 1 for x in line]
    path_matrix[paths[0]][paths[1]] = True
    path_matrix[paths[1]][paths[0]] = True
#最初はvisited、つまり訪問したことのあるノードはひとつもないので、Falseにする
visited = [False] * N
depthlist = [[] for _ in range(N)]
#再帰関数、ここが難しいかもしれない。
def dfs(now, depth):
    if visited[now]:
        return 0
    depthlist[now].append(depth)
    if depth == N - 1:
        return 1
    visited[now] = True
    total_paths = 0
    for i in range(0, N):
        if path_matrix[now][i]:
            total_paths += dfs(i, depth + 1)
    visited[now] = False
    return total_paths

# 複数経路の記録完了
dfs(0, 0)

MIN = float('inf')
for i in range(N):
    MIN = min(len(depthlist[i]), MIN)
if MIN == 0:
    print('No')
else:
    print('Yes')
    for i in range(1, N):
        print(min(depthlist[i]))

Submission status: Runtime Error

Solution code:
N,M= map(int, input().split())
A=[]
B=[]
N=1
NL=0
dn=0
ans=[]
ansx=[]
Lall=list()
moji="No"
for i in range(M):
    L=list(map(int, input().split()))
    Lall.append(L)




for j in range(M-1):
    dn=0
    for i in range(M):
        if N in Lall[i]:
            ansx.append(N)
            if Lall[i][0]==1:
                NL=1
            else:
                NL=0
        
            del Lall[i]
            dn+=1
            
        
        if i+1>=M-dn:
            break
        if len(Lall)==0:
            break
    if len(Lall)==0:
        moji="Yes"
        break
        
    ans.append(N)
    N=L[NL]
   
print(moji)
print(ansx[:-1])

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**10)
n, m = map(int, input().split())
road = [tuple(map(int, input().split())) for _ in range(m)]

table = [list() for _ in range(n+1)]
ans = [0 for _ in range(n+1)]
hush = {}

for i in range(1, n+1):
    hush[i] = False

for a, b in road:
    table[a].append(b)
    table[b].append(a)

def bfs(i):
    hush[i] = True
    rec = []
    for j in table[i]:
        if hush[j] == False:
            ans[j] = i
            hush[j] = True
            rec.append(j)
    for j in rec:
        bfs(j)

bfs(1)

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

Submission status: Runtime Error

Solution code:
def LI():return list(map(int,input().split()))
def yes():print("Yes")
def no():print("No")
from collections import deque

def main():
    n,m=LI()
    edge=[[]*n for i in range(n)]
    for i in range(m):
        a,b=LI()
        a-=1;b-=1
        edge[a].append(b)
        edge[b].append(a)
    
    ans=[-1]*(n-1)
    goal=deque([0])
    while (-1 in ans):
        g=goal.popleft()
        for i in edge[g]:
            if ans[i-1]==-1:
                ans[i-1]=g+1
                goal.append(i)
    yes()
    for i in ans:print(i)
main()

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())

result_list = [[] for i in range(m)]
for i in range(m):
    input_list = list(map(int,input().split()))
    result_list[min(input_list)-1].append(max(input_list)-1)
    
last_list = [[] for i in range(m)]
for i in range(n):
    for j in result_list[i]:
        if len(last_list[j]) == 0:
            last_list[j].append(i)
            
frag = True
for i in last_list[1:]:
    if len(i) == 0:
        print('No')
        frag = False
        break
if frag:
    print('Yes')
    for i in last_list[1:]:
        print(i[0]+1)

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
road = []
ans = [0]*n
for i in range(m):
    road.append(list(map(int,input().split())))
r1 = road[:,0]
r2 = road[:,0]
e = [1]
while ans.count(0) > 0:
    num = ans.count(0)
    r1_lis = [i for i in range(len(r1)) if r1[i] in e]
    r2_lis = [i for i in range(len(r2)) if r2[i] in e]
    [ans[r2[i]-1] = r1[i] for i in r1_lis]
    [ans[r1[i]-1] = r2[i] for i in r2_lis]
    e = [r2[i] for i in r1_lis] + [r1[i] for i in r2_lis]
    if num == ans.count(0):
        break
if num > 0:
    print('No')
else:
    print('Yes')
    [print(i for i in ans)]

Submission status: Runtime Error

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


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

d = [[0]*m for i in range(m)]
for i in range(m):
    a,b = map(int,input().split())
    d[a-1][b-1] = 1
    d[b-1][a-1] = 1
csr = csr_matrix(d)


ans =list(shortest_path(csr, indices=0, directed=False))
if ans.count(0) == 1:
    print('Yes')
    for i in range(n):
        if i != 0:
            print(int(ans[i]))
else:
    print('No')

Submission status: Runtime Error

Solution code:
#1<=A     A sench (hour)
#B<=1000  B sench (min)
#0<=H<=11 hour
#0<=M<59  minute

N,M = map(int,input().split())
AB = []
#B = []
while True:
    try:
        AB.append(list(map(int,input().split())))
        #A.append(listA[0])
        #B.append(listA[1])
    except:
        break

#N個 1-N
#M本 1-M

#print(AB)
class Room:
  def __init__(self, num, connected):
    #print('[Room.__init__]')
    self.num = num
    self.connected = connected
    self.first = 10**5
  def add(self, con):
    self.connected.append(con)
  def showinfo(self):
    #print('[Room.showinfo]')
    print(str(self.num)+' '+str(self.connected)) 

Rl = [Room(i,[]) for i in range(1,N+1)]
#Rl[0].showinfo()
#Rl[0].add(2)
#Rl[0].showinfo()
for i in range(M):
  Rl[AB[i][0]-1].add(AB[i][1])
  Rl[AB[i][1]-1].add(AB[i][0])

#for i in range(N):
#  Rl[i].showinfo()

  
Rl[0].first = 0

ma = [0]*N

def dijkstra(s):
  if(Rl[s-1].num == 1):
    Rl[s-1].first = 0
  
  if(ma[s-1]==1):
    return
  ma[s-1]+=1
    
  leng = len(Rl[s-1].connected)
  for i in range(leng):
    Rl[ Rl[s-1].connected[i]-1 ].first = min(Rl[ Rl[s-1].connected[i]-1 ].first, Rl[s-1].first+1)
  for i in range(leng):
    dijkstra(Rl[s-1].connected[i-1])

dijkstra(1)
if(sum(ma) < N):
  print('No')
else:
  print('Yes')
  for i in range(2,N):
    print(Rl[i-1].first)

Submission status: Runtime Error

Solution code:
def check(room_checked):
    for i in room_checked:
        if not i:
            return True
    return False


raw_input = list(map(int, input().strip().split()))
n = raw_input[0]
m = raw_input[1]
lines = [[0 for _ in range(m)] for __ in range(m)]
for i in range(m):
    line = list(map(int, input().strip().split()))
    a = line[0] - 1
    b = line[1] - 1
    lines[a][b] = 1
    lines[b][a] = 1
is_checked_all_room = [False for _ in range(n)]
sign = [0 for _ in range(n)]
queue = [0]
while check(is_checked_all_room):
    target = queue[0]
    is_checked_all_room[target] = True
    queue.pop(0)
    line = lines[target]
    for i, l in enumerate(line):
        if l:
            if not is_checked_all_room[i]:
                is_checked_all_room[i] = True
                sign[i] = target
                queue.append(i)
    if not queue:
        print('No')
        break
else:
    print('Yes')
    for i in range(1, n):
        print(sign[i] + 1)

Submission status: Runtime Error

Solution code:
def func(k):
    for h in lst[k]:
        if ans[h] == 0:
            ans[h] = k
            num[0] += 1
    unused.remove(k)
    new_lst = []
    for hh in  lst[k]:
        if hh in unused:
            new_lst.append(hh)
    for hh in new_lst:
        new_need.append(hh)



a = input().split(" ")
N = eval(a[0])
M = eval(a[1])
lst = [0]
ans = [0]
exist = [1]
unused = []
needed_to = [1]
for i in range(1, N + 1):
    unused.append(i)
for i in range(N):
    lst.append([])
    ans.append(0)
    exist.append(0)
ans[1] = 1
for i in range(M):
    a = input().split(" ")
    a1 = eval(a[0])
    a2 = eval(a[1])
    lst[a1].append(a2)
    lst[a2].append(a1)
    exist[a1] = 1
    exist[a2] = 1
for i in range(1, N + 1):
    lst[i] = list(set(lst[i]))
action = 1
for i in exist:
    if i == 0:
        action = 0
new_need = [1]
if action == 0:
    print("No")
else:
    while num[0] < N:
        needed_to = list(set(new_need))
        new_need = []
        for i in needed_to:
            func(i)
            needed_to.remove(i)
    print("Yes")
    for i in range(2, N + 1):
        print(ans[i])

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())

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

ikeru = [set() for _ in range(n+1)]

for i,j in tsuro:
    ikeru[i].add(j)
    ikeru[j].add(i)

ans = [0]*(n+1)
visited = [n+5]*(n+1)

def dfs(mae,heya,kaiso):
    if visited[heya] <= kaiso:
        return True
    else:
        visited[heya] = kaiso
        ans[heya] = mae
        for j in ikeru[heya]:
            dfs(heya, j, kaiso+1)
        return True

hantei = True
dfs(0,1,0)
for i in range(1, n+1):
    if visited[i] == n+5:
        hantei = False
        break
if hantei:
    print('Yes')
    for k in range(2,n+1):
        print(ans[k])
else:
    print('No')

Submission status: Runtime Error

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

N, M = map(int, input().split())
a = np.zeros((N, N))

for i in range(M):
    A, B = map(int, input().split())
    if a[A-1][B-1] == 0:
        a[A-1][B-1] = 1
        a[B-1][A-1] = 1

a = shortest_path(a, indices=0, return_predecessors=True)

if -1 in np.sign(a[1][1:]):
    print('No')
    exit()

print('Yes')

print(*a[1][1:]+1, sep="\n")

Submission status: Runtime Error

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

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

ABsT = ABs.T
row = list(ABsT[0]-1) + list(ABsT[1]-1)
col = list(ABsT[1]-1) + list(ABsT[0]-1)
data = [1] * (2 * M)

csr = csr_matrix((data, (row, col)), shape=(N, N))
from_starts, procs = dijkstra(csr, indices=[0], return_predecessors=True)
proc = procs[0]
 
print(csr.toarray())
print(proc)
if -9999 in proc[1:]:
  print('No')
else:
  print('Yes')
  for i in range(N-1):
    print(int(proc[i+1]) + 1)

Submission status: Runtime Error

Solution code:
MAX_INT = 10**6
N, M = map(int, input().split())
room = [set() for _ in range(N+1)]
for i in range(M):
    a, b = map(int, input().split())
    room[a].add(b)
    room[b].add(a)

dis = [MAX_INT] * (N + 1)
sign = [-1] * (N + 1)
dis[1] = 0
aa = [False] * (N + 1)
def sign_root(n):
    if not aa[n]:
        for i in room[n]:
            if dis[n] + 1 < dis[i]:
                sign[i] = n
                dis[i] = dis[n] + 1
                sign_root(i)
    aa[n] = True
sign_root(1)
if MAX_INT in dis[2:]:
    print("No")
else:
    print("Yes")
    for i in sign[2:]:
        print(i)

Submission status: Runtime Error

Solution code:
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:
N, M = map(int, input().split())
A, B = list(), list()
for _ in range(M):
    line = list(map(int, input().split()))
    A.append(line[0]-1)
    B.append(line[1]-1)

cave = [set() for _ in range(M)]
for i in range(M):
    cave[A[i]].add(B[i])
    cave[B[i]].add(A[i])

del A
del B
del line

visited = [False] * M
guide = [-1] * N
queue = [0]
while queue:
    current = queue.pop(0)
    visited[current] = True
    for nextRoom in cave[current]:
        if not visited[nextRoom]:
            queue.append(nextRoom)
            if guide[nextRoom] == -1:
                guide[nextRoom] = current

print('Yes')
for g in guide[1:]:
    print(g+1)

Submission status: Runtime Error

Solution code:
def cape(iri):
    ima = set()
    for i in iri:
        for j in root[i]:
            if ans[j] == 0:
 #               print("now", i, j, ima)
                ans[j] = i
 #               print(root[j])
                root[j] -= iri #ここが重そう
 #               print(root[j])
                ima.add(j) #ここも重そう
#                print(ima)
#    print(ima)
    if ima != set():
        cape(ima)

N, M = map(int, input().split())
root = [set() for i in range(N + 1)]
ans = [0 for i in range(N + 1)]
for i in range(M):
    a, b = map(int, input().split())
    root[a].add(b)
    root[b].add(a)
#print(root)
cape({1})
print("Yes")
for i in range(2, N + 1):
    print(ans[i])

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import collections
import itertools as it
import math
#import numpy as np
 
#  = input()
#  = int(input())
n, m  = map(int, input().split())
#  = list(map(int, input().split()))
#  = [int(input()) for i in range(N)]
#
# c = collections.Counter()


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

chikai = [[-1, -1] for _ in range(n+1)]
chikai[1] = [-1, 0]

def set_shirube(n, v):
    #print(n, v, node[n])
    for n_ in node[n]:
        if chikai[n_][1] == -1:
            chikai[n_] = [n, v+1]
            set_shirube(n_, v+1)
        else:
            if chikai[n_][1] > v+1:
                chikai[n_] = [n, v+1]

set_shirube(1, 0)
#print(chikai)

for l in chikai[1:]:
    r, v = l
    if v == 0:
        print('Yes')
    else:
        print(r)

Submission status: Runtime Error

Solution code:
from collections import deque
n, m = map(int, input().split())
li = [list(map(int, input().split())) for _ in range(m)]

ans = [deque([]) for _ in range(m+10)]
ans2 = [[] for _ in range(m+10)]
for i in range(m):
    s = li[i][0]
    t = li[i][1]

    ans[s].append(t)
    ans[t].append(s)


stack = deque([1])
while stack:
    v = stack[0]

    if ans[v]:
        w = ans[v].popleft()
        if ans2[w] == []:
            ans2[w].append(v)
        stack.append(w)
    else:
        stack.popleft()

print('Yes')
for i in range(2, m+1):
    print(ans2[i][0])

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

# from math import gcd
from fractions import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement
import copy

N, M = [int(_) for _ in input().split()]
AB = [[int(_) for _ in input().split()] for i in range(M)]

goal = 1
rets = []
road = {i:[] for i in range(1, N+1)}

for A, B in AB:
    road[A] += [B]
    road[B] += [A]

ret, retind = [], []

def dfs(ind, inds, dis):

    global goal, ret, retind

    if ind in inds:
        return

    inds += [ind]
    dis += 1

    if ind == goal:
        ret += [dis]
        retind += [inds]
        return

    for i in road[ind]:
        dfs(i, copy.copy(inds), dis)

for start in range(2, N+1):
    ret, retind = [], []
    dfs(start, [], 0)
    if ret:
        rets += [retind[ret.index(min(ret))][1]]
    else:
        rets += [None]

ch = list(set(rets))
if len(ch) == 1 and ch[0] == None:
    print("No")
else:
    print("Yes")
    for i in rets:
        print(i)

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
l = list(list(map(int, input().split())) for _ in range(m))
sign = list(list() for _ in range(m+1))
c = [0]*(m+1)
for i in l:
    sign[i[0]].append(i[1])
    sign[i[1]].append(i[0])
cnt = 0
x = [1]
k = []
for _ in range(m):
    for i in x:
        a = i
        x = []
        for j in sign[a]:
            if c[j] == 0:
                c[j] = a
                cnt += 1
            x.append(j)
if cnt >= m-1:
    print('Yes')
    for i in c[2:]:
        print(i)
else:
    print('No')

Submission status: Runtime Error

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

connect_list = [set() for _ in range(N)]
ranking = [set() for _ in range(N)]
ranked_set = set()
full_set = {i for i in range(1, N+1)}


def do_ranking(set, rank):
    global connect_list, ranking, ranked_set, full_set
    if ranked_set == full_set:
        return 0
    for j in list(set):
        for i in list(connect_list[j-1]):
            if i not in ranked_set:
                ranking[rank].add(i)
                ranked_set.add(i)
    do_ranking(ranking[rank], rank+1)



for A, B in AB:
    connect_list[A-1].add(B)
    connect_list[B-1].add(A)
ranking[0] = connect_list[0]
ranked_set = ranked_set | ranking[0]
ranked_set.add(1)
do_ranking(ranking[0], 1)

root_list = [0]*N
root_list[0] = "Yes"
count = 0
no_flag = False
for i in range(1, N):
    flag = True
    j = 0
    while flag:
        if len(ranking[j]) == 0:
            no_flag = True
            break
        seki = connect_list[i] & ranking[j]
        if 1 in connect_list[i]:
            root_list[i] = 1
            flag = False
        elif len(seki) != 0:
            print(seki)
            root_list[i] = list(seki)[0]
            flag = False
        else:
            j += 1
    if no_flag:
        print("No")
        break
if no_flag == False:
    for i in root_list:
        print(i)

Submission status: Runtime Error

Solution code:
def distcascade(dist,link,v,d):
  nextdis = set()
  for s in link[v]:
    if s != 1:
      if s not in dist:
        dist[s] = d
        nextdis.add(s)
      else:
        dist[s] = min(dist[s],d)
  for x in nextdis:
    distcascade(dist,link,x,d+1)

n,m = map(int,input().split())
ab = [[0]*2]*m
for i in range(m):
  ab[i] = list(map(int,input().split()))
linked = dict()
for i in range(m):
  if ab[i][0] not in linked:
    linked[ab[i][0]] = {ab[i][1]}
  else:
    linked[ab[i][0]].add(ab[i][1])
  if ab[i][1] not in linked:
    linked[ab[i][1]] = {ab[i][0]}
  else:
    linked[ab[i][1]].add(ab[i][0])
sol = 1
for i in range(1,n+1):
  if i not in linked:
    sol = 0
if sol == 0:
  print("No")
else:
  dist = {}
  distcascade(dist,linked,1,1)
  signboard = {}
  for i in range(2,n+1):
    if dist[i] == 1:
      signboard[i] = 1
    else:
      for s in linked[i]:
        if dist[s] == dist[i]-1:
          signboard[i] = s
  print("Yes")
  for i in range(2,n+1):
    print(signboard[i])