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: Wrong Answer

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

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


#d = [float("inf")*n for i in range(n)]
d = [[float("inf") for i in range(n)] for i in range(n)] 
for i in range(m):
    a,b = map(int,input().split())
    d[a-1][b-1] = 1
    d[b-1][a-1] = 1

ans = dijkstra(0,n,m,d)

if ans.count(0) == 1:
    print('Yes')
    for i in range(n):
        if i != 0:
            print(int(ans[i]))
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import sys
import os
from collections import deque

def file_input():
    f = open('ABC168/input.txt', 'r')
    sys.stdin = f

def main():
    if os.getenv("ENV")=='LOCAL':
        file_input()

    N,M=map(int, input().split())
    A=[0]*M
    B=[0]*M
    r={}
    for i in range(M):
        A[i],B[i]=map(int, input().split())
        # print("A:"+str(A[i])+" B:"+str(B[i]))
        if A[i] not in r:
            r[A[i]]=[B[i]]
        else:
            r[A[i]].append(B[i])
        if B[i] not in r:
            r[B[i]]=[A[i]]
        else:
            r[B[i]].append(A[i])
        # print(tmp[A[i]-1])
    # print(r)

    q=deque()
    q.append(1)
    visited=set()
    out=[0]*(N-1)
    while len(q)>0:
        # print("q="+str(q))
        position=q.pop()
        # print("p="+str(position))
        visited.add(position)
        for des in r[position]: #今いる場所から行ける場所を探索
            if des in visited:  #すでに訪問済み
                continue
            if des in q:    #ループよけ 2→2みたいな
                continue
            q.append(des)   #行ける場所だった場合キューに追加
            # print("destination="+str(des)+" p="+str(position)+" q="+str(q))
            out[des-2]=position
    # print(visited)



    print('Yes')
    [print(x) for x in out]

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
N, M = map(int, input().split())
C = [list(map(int, input().split())) for i in range(M)]

def bfs(room, now):
    # print(room, now)
    plan = deque([])
    # for r in room:
    #     plan.append(r)
    plan.append(room)
    # print(plan)
    visited[1][0] = True
    while plan:
        nextque = plan.popleft()
        # print(nextque)
        for i in PATH[now]:
            if visited[i][0] == True:
                # print('true')
                continue
            else:
                # for r in PATH[next]:
                #     plan.append(r)
                plan.append(PATH[i])
                # print(plan)
                visited[i][0] = True
                visited[i][1] = now
        now = i

if __name__ == '__main__':
    PATH = [[] for i in range(N+1)]
    
    for i in range(M):
        PATH[C[i][0]].append(C[i][1])
        PATH[C[i][1]].append(C[i][0])
    # print(PATH)
    visited = [[False,0] for i in range(N+1)]
    bfs(PATH[1], 1)
    # print(visited)
    for i in range(2,N+1):
        print(visited[i][1])

Submission status: Wrong Answer

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

adj = {}
for x in range(m):
    a,b = [int(x) for x in input().split()]
    if a in adj:
        adj[a].append(b)
    else:
        adj[a] = [b]

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

q = []
dist = {}
prev = {}
for v in adj:
    dist[v] = 9999999
    prev[v] = None
    q.append(v)
dist[1] = 0


while len(q) != 0:
    m = 9999999
    minelemindex = None
    for x in range(len(q)):
        if q[x] < m:
            minelemindex = x
            m = q[x]

    u = q[minelemindex]
    q.pop(minelemindex)

    for v in adj[u]:
        alt = dist[u] + 1
        if alt < dist[v]:
            dist[v] = alt
            prev[v] = u

countnone = 0
for x in adj:
    if prev[x] == None:
        countnone += 1

def lencoso(st):
    if st == None:
        return 0
    return lencoso(prev[st]) + 1

if countnone > 1:
    print("No")
else:
    print("Yes")
    for x in range(2,len(adj)+1):
        print(prev[x])

Submission status: Wrong Answer

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

adj = {}
for x in range(m):
    a,b = [int(x) for x in input().split()]
    if a in adj:
        adj[a].append(b)
    else:
        adj[a] = [b]

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

q = []
dist = {}
prev = {}
for v in adj:
    dist[v] = 9999999
    prev[v] = None
    q.append(v)
dist[1] = 0


while len(q) != 0:
    m = 9999999
    minelemindex = None
    for x in range(len(q)):
        if q[x] < m:
            minelemindex = x
            m = q[x]

    u = q[minelemindex]
    q.pop(minelemindex)

    for v in adj[u]:
        alt = dist[u] + 1
        if alt < dist[v]:
            dist[v] = alt
            prev[v] = u

countnone = 0
for x in adj:
    if prev[x] == None:
        countnone += 1

def lencoso(st):
    if st == None:
        return 0
    return lencoso(prev[st]) + 1

if countnone > 1:
    print("No")
else:
    print("Yes")
    for x in range(1,len(adj)+1):
        print(prev[x])

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    N,M = map(int, input().split())
    r = [[] for i in range(N)]
    for i in range(M):
        a, b = map(int, input().split())
        r[a-1].append(b-1)
        r[b-1].append(a-1)
    print(r)

    p=[-1]*N
    q=deque([0])
    while q:
        i=q.popleft()
        for j in r[i]:
            if p[j] == -1:
                p[j] = i
                q.append(j)
    print('Yes')
    for i in range(1,N):
        print(p[i]+1)

main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
from collections import deque
q = []
for i in range(m):
    a,b = map(int,input().split())
    if b > a:
        a,b = b,a
    q.append([a,b])
q.sort()
q = deque(q)
d = [-1]*(n+1)
michi = [-1]*(n+1)

d[1] = 0

while len(q) >= 1:
    p = q.popleft()
    a = p[0]
    b = p[1]

    if d[a] >= 0 and d[b] >= 0:
        if d[a] > d[b]:
            d[a] = d[b] + 1
            michi[a] = b
        elif d[b] > d[a]:
            d[b] = d[a] + 1
            michi[b] = a
    elif d[a] >= 0:
        d[b] = d[a] + 1
        michi[b] = a
    elif d[b] >= 0:
        d[a] = d[b] + 1
        michi[a] = b
    else:
        q.append([a,b])

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

Submission status: Wrong Answer

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

visited = [False] * N
dist = [float('inf')] * N
def bfs(u):
    q = queue.Queue()
    q.put((u, 0))
    while not q.empty():
        (v, d) = q.get()
        visited[v] = True
        dist[v] = min(dist[v], d)
        for e in edges[v]:
            if visited[e]:
                continue
            q.put((e, d + 1))

dist[0] = 0
bfs(0)
print("Yes")
for x in dist[1:]:
    print(x)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
d={}
for i in range(m):
	x,y=map(int,input().split())
	if x in d:
		d[x].append(y)
	else:
		d[x]=[y]
	if y in d:
		d[y].append(x)
	else:
		d[y]=[x]

parent=[0]*(n+1)
bfs=[1]
visited=set([1])
while len(bfs)!=0:
	x=bfs.pop(0)
	visited.add(x)
	for i in d[x]:
		if i not in visited:
			bfs.append(i)
			parent[i]=x
			visited.add(i)


if len(visited)==n:
	print('YES')
	for i in range(2,n+1):
		print(parent[i])
else:
	print('NO')

Submission status: Wrong Answer

Solution code:
from collections import deque
dic = {}
def make_map(a, b, dic):
    if a in dic.keys():
        dic[a].append(b)
    else:
        dic[a] = [b]
N, M = map(int, input().split())
for m in range(M):
    a, b = map(int, input().split())
    make_map(a-1, b-1, dic)
    make_map(b-1, a-1, dic)
queue = deque([0])
count = 0
dekai = 10**5
lenlist = [dekai]*N
lenlist[0] = 0
while queue:
    a = queue.popleft()
    for i in dic[a]:
        if lenlist[i] ==dekai or a == 0:
            queue.append(i)#今までいったことないなら見るリストに追加
            lenlist[i] = a #今いる座標の距離+!が次の座標の距離
for n in range(1,N, 1):
    print(lenlist[n]+1)

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())
d = {}
ans = [0] * (n)
for _ in range(m):
    a, b = map(int, input().split())
    if not a in d.keys():
        d[a] = [b]
    else:
        d[a].append(b)
    if not b in d.keys():
        d[b] = [a]
    else:
        d[b].append(a)

q = deque([1])
alr = [1]
while not len(q) == 0:
    x = q.popleft()
    for i in d[x]:
        if i in alr:
            continue
        if ans[i-1] == 0:
            ans[i-1] = x
        alr.append(i)
        q.append(i)

if 0 in ans:
    print('No')
else:
    print('Yes')
    for j in ans[1:]:
        print(j)

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
  N,M=map(int,input().split())
  r=[[]for i in range(N)]
  d,p=[10**6]*N,[10**6]*N

  for i in range(M):
    a,b=map(int,input().split())
    r[a-1].append(b-1)
    r[b-1].append(a-1)

  q=deque([0])
  p[0],d[0]=-1,0

  while len(q)!=0:
    i=q.pop()
    for j in r[i]:
      if d[j]==10**6:
        d[j],p[j]=d[i]+1,i
        q.append(j)

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

main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import numpy as np

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())
A=np.array(A)
B=np.array(B)

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

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

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


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

else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
from collections import deque
q = deque([])
for i in range(m):
    q.append(list(map(int,input().split())))
d = [-1]*(n+1)
miti = [-1]*(n+1)
d[1] = 0
while len(q) >= 1:
    p = q.popleft()
    a = p[0]
    b = p[1]

    if d[a] >= 0 and d[b] >= 0:
        if d[a] > d[b]:
            d[a] = d[b] + 1
            miti[a] = b
        elif d[b] > d[a]:
            d[b] = d[a] + 1
            miti[b] = a
    elif d[a] >= 0:
        d[b] = d[a] + 1
        miti[b] = a
    elif d[b] >= 0:
        d[a] = d[b] + 1
        miti[a] = b
    else:
        q.append([a,b])

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

Submission status: Wrong Answer

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

mark = list(int() for _ in range(N))
rs = [0]*M
rg = [0]*M
mr = [0]*N

for i in range (M):
    A,B = map(int,input().split())

    rs[i] = A
    rg[i] = B

    if rs[i] == 1:
        mr[B-1] = 1

    if rg[i] == 1:
        mr[A-1] = 1


for i in range (1,N):
    for j in range (N):

        if mr[j] == i:

            for l in range (M):

                if rs[l] == j+1:
                    if mr[rg[l]-1] == 0:
                        mr[rg[l]-1] = j+1
                    

                if rg[l] == j+1:
                    if mr[rs[l]-1] == 0:
                        mr[rs[l]-1] = j+1

if 0 in mr:
    print("No")

else:

    print("Yes")

    for i in range (1,N):
        print(mr[i])

Submission status: Wrong Answer

Solution code:
import collections
N, M = map(int, input().split())
G = collections.defaultdict(list)
for _ in range(M):
    a, b = map(int, input().split())
    G[a].append(b)
    G[b].append(a)
    
dist = [-1] * (N + 1)
que = collections.deque()

dist[1] = 0
que.append(1)

while len(que):
    v = que.popleft()
    for nv in G[v]:
        if dist[nv] != -1:
            continue
        dist[nv] = dist[v] + 1
        que.append(nv)

memo = collections.defaultdict(int)
memo[0] = 1


for i in range(2, N+1):
    memo[dist[i]] = i
for dis in dist[2:]:
    print(memo[dis-1])

Submission status: Wrong Answer

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

mark = list(int() for _ in range(N))
rs = [0]*M
rg = [0]*M
mr = [0]*N

for i in range (M):
    A,B = map(int,input().split())

    rs[i] = A
    rg[i] = B

    if rs[i] == 1:
        mr[B-1] = 1

    if rg[i] == 1:
        mr[A-1] = 1


for i in range (1,N):
    for j in range (N):

        if mr[j] == i:

            for l in range (M):

                if rs[l] == j+1:
                    if mr[rg[l]-1] == 0:
                        mr[rg[l]-1] = i+1
                    

                if rg[l] == j+1:
                    if mr[rs[l]-1] == 0:
                        mr[rs[l]-1] = i+1

if 0 in mr:
    print("No")

else:

    print("Yes")

    for i in range (1,N):
        print(mr[i])

Submission status: Wrong Answer

Solution code:
import sys
from math import cos, radians, pi, sqrt
import numpy as np

head = input().split()
N = int(head[0])
M = int(head[1])
inputs = [input() for i in range(M)]

i = 1
dic = {}
for i in range(0, M):
#	print("探索%d回目" % i)
	param = inputs[i].split()
	A = param[0]
	B = param[1]

	if A in dic.keys():
		dic[A].append(B)
	else:
		dic[A] = []
		dic[A].append(B)

	if B in dic.keys():
		dic[B].append(A)
	else:
		dic[B] = []
		dic[B].append(A)
	
depth = {'1': 0}
que = dic['1']
count=1

while not que == []:
	next_que = []
	for room in que:
		if room in depth.keys():
			continue

		depth[room] = count
		for next_room in dic[str(room)]:
			if not next_room in next_que:
				next_que.append(next_room)
	count += 1
	que = next_que

dist = {}
for i in range(1, N+1):
	for room, dep in depth.items():
		if depth[str(i)]-1 == dep:
			dist[str(i)] = room
			break

print("yes")
for opt in dist.items():
	print(opt[1])

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
room = []
ans = []
for i in range(1,n):
  room.append([i,i])
  ans.append(0)
room.append([n,n])
ab = []
for i in range(m):
  a,b = map(int,input().split())
  ab.append([min(a,b)-1,max(a,b)-1])
ab.sort()
for i in range(len(ab)):
  if(room[ab[i][0]][1]==1):
    ans[ab[i][1]-1]=room[ab[i][0]][0]
    room[ab[i][1]][1]=1
print("Yes")
for i in range(len(ans)):
  print(ans[i])

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import math
from collections import deque

N , M = map(int,input().split())
miti = [ [] for _ in range(N)]
for m in range(M):
    a , b = map(int , input().split())
    if b-1 != 0:
        miti[a-1].append(b-1)
    if a-1 != 0:
        miti[b-1].append(a-1)
visit = [0] * N
point = [ -1 for _ in range(N)]

def bfs():
    G = deque(miti[0])
    visit[0] = 1
    while G:
        m = G.popleft()
        for n in miti[m]:
            if visit[n] == 0 :
                visit[n] = 1
                point[n] = m
                G.append(n)

def solve():
    bfs()
    print("Yes")
    for a in point[1::]:
        print(a+1)

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
AB = []
ans = [-1] * (n) #####

edge = [[] for _ in range(n)] #edge[i] := 頂点iから伸びてる辺の行き先のリスト #####

for i in range(m):
    a,b = map(int,input().split())
    a-=1; b-=1 #####
    edge[a].append(b)    
    edge[b].append(a)    
    
import collections
que = collections.deque()
que.append(0) #####
    
while que:
    x = que.popleft()
    
    for to in edge[x]:
        a = x
        b = to
        
        if ans[b] == -1: #####
            ans[b] = x + 1 #####
            que.append(b)
            
print("Yes")
print(*ans,sep="\n")

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
AB = []
ans = [0] * (n-1)

edge = [[] for _ in range(n+1)] #edge[i] := 頂点iから伸びてる辺の行き先のリスト

for i in range(m):
    a,b = map(int,input().split())
    edge[a].append(b)    
    edge[b].append(a)    
    
import collections
que = collections.deque()
que.append(1)
    
while que:
    x = que.popleft()
    
    for to in edge[x]:
        a = x
        b = to
        
        if x < a:
            break
        
        if a == x:
            if ans[b-2] == 0:
                ans[b-2] = x
                que.append(b)
        elif b == x:
            if ans[a-2] == 0:
                ans[a-2] = x
                que.append(a)
            
if 0 in ans:
    print("No")
else:
    print("Yes")
    
    for i in ans:
        print(i)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**9)


INF = 10**20
def main():
    N,M = map(int,input().split())

    graph = [[] for _ in range(N)]
    for i in range(M):
        A,B = map(int,input().split())
        graph[B-1].append(A-1)
        graph[A-1].append(B-1)

    stack = deque([(0,0)])
    visited = [(0,0)]*N
    _visited = set()
    while len(stack) > 0:
        x,depth = stack.pop()
        for next in graph[x]:
            if not next in _visited:
                visited[next] = x,depth+1
                stack.append((next,depth+1))
                _visited.add(next)
            else:
                _, cd = visited[next]
                if cd > depth+1:
                    visited[next] = x,depth+1

    if len(_visited) != N:
        print("No")
    else:
        print("Yes")
        for i,_ in visited[1:]:
            print(i+1)



if __name__ == "__main__":
  main()

Submission status: Wrong Answer

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


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

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

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
AB = []
ans = [0] * (n-1)

for i in range(m):
    AB.append(list(map(int,input().split())))
    
import collections
que = collections.deque()
que.append(1)
    
while que:
    x = que.popleft()
    
    for i in AB:
        a = i[0]
        b = i[1]
        
        if a == x and ans[b-2] == 0:
            ans[b-2] = x
            que.append(b)
            AB.remove(i)
        elif b == x and ans[a-2] == 0:
            ans[a-2] = x
            que.append(a)
            AB.remove(i)
            
if 0 in ans:
    print("No")
else:
    print("Yes")
    
    for i in ans:
        print(i)

Submission status: Wrong Answer

Solution code:
N, M = map(int,input().split())
graph = [[] for n in range(N+1)]
for _ in range(M):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
# 入力例 1の場合
# graph : [[], [2], [1, 3, 4], [2, 4], [3, 2]] graphのインデックスが部屋名
# graph[2] : 部屋2は、1,3,4と繋がっている
# graph[4] : 部屋4は、3,2と繋がっている

#次に探索をする部屋番号をストックしておく。まずは部屋番号1から探索を始めるので、１を入れておく
q = [1]
#ans[部屋番号]=道標が指す部屋番号とする。探索していない部屋を'No'として表す。
ans = ['No' for n in range(N+1)]
ans[1] = 1 #ans[1]
while q: #qの中身がなくなったらbreak
    # 現在地を指定（キューの先頭）するとともに、qから先頭を削除する。　一番最初の現在地は1になる。
    now = q.pop(0)
    for edge in graph[now]:
        if ans[edge] != 'No':
            continue
        ans[edge] = now
        q.append(edge)

if not 'No' in ans:
    print('Yes')
    for n in range(2,N+1):
        print(ans[n])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**9)


INF = 10**20
def main():
    N,M = map(int,input().split())

    graph = [[] for _ in range(N)]
    for i in range(M):
        A,B = map(int,input().split())
        graph[B-1].append(A-1)
        graph[A-1].append(B-1)

    stack = deque([0])
    ans = [0]*N
    visited = set()
    while len(stack) > 0:
        x = stack.pop()
        for next in graph[x]:
            if not next in visited:
                ans[next] = x
                visited.add(next)
                stack.append(next)

    if len(visited) != N:
        print("No")
    else:
        print("Yes")
        for i in ans[1:]:
            print(i+1)



if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:

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

from collections import deque

d=deque()
d.append(0)
ans = [0]*N
while len(d)!=0:
    now = d.popleft()
    for to in a[now]:
        if ans[to]==0:
            ans[to]=ans[now]+1
            d.append(to)
print("Yes")
for i in range(N-1):
    print(ans[i+1])

Submission status: Wrong Answer

Solution code:
from _collections import deque
n,m=map(int,input().split())
M=[[] for _ in range(n)]
ANS=[-1]*n
ANS[0]=0
for i in range(m):
    a,b=map(int,input().split())
    M[b-1].append(a-1)
    M[a-1].append(b-1)

q=deque([0])

while q:
    s=q.popleft()
    for x in M[s]:
        if ANS[x]!=-1:
            continue
        q.append(x)
        ANS[x]=s
print('Yes')
for ans in ANS[:1]:
    print(ans+1)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def WFS(fs, l, end):
    nfs = set([])
    nl = l.copy()
    flg = False
    for i in range(len(l)):
        if l[i][0] in fs and not l[i][1] in end:
            nfs.add(l[i][1])
            rs.append([l[i][1],l[i][0]])
            nl[i] = [0,0]
            flg = True
        if l[i][1] in fs and not l[i][0] in end:
            nfs.add(l[i][0])
            rs.append([l[i][0],l[i][1]])
            nl[i] = [0,0]
            flg = True
    end = end | nfs

    # print(nl)
    if flg:
        WFS(nfs,nl,end)

nm = input().split()
n = int(nm[0])
m = int(nm[1])

l = []
rs = []

for _ in range(m):
    l.append(input().split())



WFS({'1'},l,{'1'})
# print(rs)
srs = sorted(rs)
print('Yes')
for i in srs:
    if srs[0] != 1:
        print(i[1])

Submission status: Wrong Answer

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


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

Submission status: Wrong Answer

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


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

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs2(g,n,m):
    pre=[0 for _ in range(n+1)]
    pre[1]=1
    q=deque([1])
    while q:
        x=q.popleft()
        for i in range(len(g[x])):
            if pre[g[x][i]]==0:
                q.append(g[x][i])
                pre[g[x][i]]=x
    return pre

def main2():
    #normal input
    n,m=map(int,input().strip().split())
    g=[[] for _ in range(n+1)]
    for _ in range(m):
        a,b=map(int,input().strip().split())
        g[a].append(b)
        g[b].append(a)
        
    pre=bfs2(g,n,m)
    
    print("yes" if 0 not in pre[1:] else "No")
    for i in range(2,len(pre)):
        print(pre[i])

if __name__=="__main__":
    main2()

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
l = [[] for i in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    l[a].append(b)
    l[b].append(a)
ans = [0] * (n + 1)
f = [0] * (n + 1)
d = deque()
d.append(1)
print(len(d))
while len(d) > 0:
    k = d.popleft()
    f[k] = 1
    for i in l[k]:
        if f[i] == 1:
            continue
        ans[i] = k
        d.append(i)
        f[i] = 1
for i in range(2, n + 1):
    if ans[i] == 0:
        print("No")
        exit()
print("Yes")
for i in range(2, n + 1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
import numpy as np
# スペース区切りの整数の入力
N, M = map(int, input().split())

Root = []
for _ in range(M):
    A_, B_ = map(int, input().split())
    Root.append([A_, B_])
    
root = np.array(Root).reshape(-1,2)


# 入り口からの距離と道知るベを測る
depth = np.array([-1] * N)
toward = depth

## 1 番の部屋は距離0
depth[0] = 0

# 終わったか
Finflag = False

# 距離が近い順に埋めていく
for i in range(N):
    # 距離iの部屋を表す複数のindex
    indices = np.where(depth==i)[0]
    
    rooms = []
    newdepth = i+1
    for index in indices:
        # index につながる部屋を抽出
        x, y = np.where(root == index+1)
        # 該当する場所にdepthと道しるべを置く
        #print(x,y)
        room = root[x, 1 - y]
        #print(room)
        depth[room - 1] = newdepth
        toward[room - 1] = index+1
        root = np.delete(root,obj=x,axis=0)

    # 処理が終われば終了
    if not np.any(depth == -1):
        Finflag = True
        break

# output
if Finflag:
    print("Yes")
    for tow in toward[1:]:
        print(tow)
else:
    print("No")

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import numpy as np
# スペース区切りの整数の入力
N, M = map(int, input().split())

Root = []
for _ in range(M):
    A_, B_ = map(int, input().split())
    Root.append([A_, B_])
    
root = np.array(Root).reshape(-1,2)


# 入り口からの距離と道知るベを測る
depth = np.array([-1] * N)
toward = depth

## 1 番の部屋は距離0
depth[0] = 0

# 終わったか
Finflag = False

# 距離が近い順に埋めていく
for i in range(N):
    # 距離iの部屋を表す複数のindex
    indices = np.where(depth==i)[0]
    
    rooms = []
    newdepth = i+1
    for index in indices:
        # index につながる部屋を抽出
        x, y = np.where(root == index+1)
        # 該当する場所にdepthと道しるべを置く
        #print(x,y)
        room = root[x, 1 - y]
        print(room)
        depth[room - 1] = newdepth
        toward[room - 1] = index+1
        root = np.delete(root,obj=x,axis=0)

    # 処理が終われば終了
    if not np.any(depth == -1):
        Finflag = True
        break

# output
if Finflag:
    print("Yes")
    for tow in toward[1:]:
        print(tow)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
print("Yes")
print(6)
print(5)
print(6)
print(1)
print(1)