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:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p1 = []
p2 = []
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p1.append(a)
    p2.append(b)
d = [1, ]
c = [0, ]
l = 0
flag = True
for _ in range(1, n):
    for i in range(m):
        if p1[i] == d[l]:
            d.append(p2[i])
            c.append(p1[i])
        if p2[i] == d[l]:
            d.append(p1[i])
            c.append(p2[i])
    if len(d) > l:
        l += 1
    else:
        flag = False
        break
con = []
print(d)
print(c)
for i in range(2, n+1):
    for y, j in enumerate(d):
        flfl = True
        if j == i:
            con.append(c[y])
            flfl=False
            break
    if flfl:
        con.append(0)
        break

if 0 in con:
    print('No')
else:
    print('Yes')
    for i in con:
        print(i)

Submission status: Wrong Answer

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
#dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])}
ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda :int(input())
ip = lambda :[int(w) for w in input().split()]

n,m = ip()
graph = {i:[] for i in range(1,n+1)}
for i in range(m):
    a,b = ip()
    graph[a].append(b)
    graph[b].append(a)

start = 1
nodes = list(graph.keys())
d = {i:float('inf') for i in nodes}
parent = {i:-1 for i in nodes}
q = set([i for i in nodes])
d[start] = 0

while len(q):
    mn = float('inf')
    for v in nodes:
        if d[v] < mn and v in q:
            mn = d[v]
            u = v
    q.remove(u)
    for v in graph[u]:
        if d[u]+1 < d[v] and v in q:
            d[v] = d[u] + 1
            parent[v] = u

if float('inf') in list(d.values()):
    print("No")
    exit()
print("Yes")
for i in range(2,n+1):
    print(d[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

import numpy as np

N, M = list(map(int, input().split()))
tsuro = [list(map(int, input().split())) for _ in range(M)]
tsuro = np.array(tsuro)
arr = list(range(2, N + 1))
tsuro = np.sort(tsuro, axis=1)
order = np.argsort(tsuro[:, 0])
tsuro = tsuro[order]

depth_array = np.ones(N) * -1
depth_array[0] = 0
ans_array = np.zeros(N)
tsuro = deque(tsuro.tolist())
counts = 0
success_flag = False
while tsuro:
    if counts > 3 * N:
        break
    room_a, room_b = tsuro.popleft()
    room_a, room_b = room_a - 1, room_b - 1
    if depth_array[room_a] != -1 and depth_array[room_b] != -1:
        continue
    elif depth_array[room_a] != -1:
        depth_array[room_b] = depth_array[room_a] + 1
        ans_array[room_b] = room_a + 1
    elif depth_array[room_b] != -1:
        depth_array[room_a] = depth_array[room_b] + 1
        ans_array[room_a] = room_b + 1
    else:
        tsuro.append([room_a + 1, room_b + 1])
    if -1 not in depth_array:
        break
    counts += 1
if -1 not in depth_array:
    print('Yes')
    for ans in ans_array[1:]:
        print(int(ans))
else:
    print('No')

Submission status: Wrong Answer

Solution code:
# d
import numpy as np
n, m = [int(i) for i in input().split()]
a = [0]*m
b = [0]*m
ans = np.array([0]*(n))
count = [0]*n
roop = 0
A = np.array([1])
for i in range(m):
    a[i], b[i] = [int(j)-1 for j in input().split()]
    if a[i] == 0:# and ans[b[i]] == 0:
        ans[b[i]] = 1
        count[b[i]] = 1
        A = np.append(A,b[i]+1)
    elif b[i] == 0:# and ans[a[i]] == 0:
        ans[a[i]] =1
        np.append(A,a[i]+1)
        count[a[i]] = 1
# ここまででansの要素（部屋番号）には1と繋がれている部屋の案内が1となっている．
# あと，Aには一回で1に行ける部屋のリストが出来ている．
# print(A)
# print(ans)
while np.any(ans[1:] == 0) == True:
    roop += 1
    B = np.array([])
    if roop == 1:
        for i in range(m):
            # まずai部屋の看板ansについて考える
#             print("a[i] : " + str(a[i]) + ", b[i] : " +  str(b[i]))
            if np.any(a[i] == A-1):
                if ans[b[i]] == 0:
                    ans[b[i]] = a[i]+1
                    B = np.append(B, b[i]+1)
#                     print("上 : " + str(ans))
            # 部屋biについても同様に
            elif np.any(b[i] == A-1):
                if ans[a[i]] == 0:
                    ans[a[i]] = b[i]+1
                    B = np.append(B, a[i]+1)
#                     print("下 : " + str(ans))
            A = np.append(A, B)
#     print(roop)
#     print(A)
    if roop == 10:
#         print("break")
        break
#
# print(ans)
flag = 0
if np.any(ans[1:] == 0):
    flag = 0
else:
    flag = 1
    
if flag == 0:
    print('No')
elif flag == 1:
    print('Yes')
    for i in range(1, n):
        print(ans[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

import numpy as np

N, M = list(map(int, input().split()))
tsuro = [list(map(int, input().split())) for _ in range(M)]
tsuro = np.array(tsuro)
arr = list(range(2, N + 1))
tsuro = np.sort(tsuro, axis=1)
order = np.argsort(tsuro[:, 0])
tsuro = tsuro[order]

depth_array = np.ones(N) * -1
depth_array[0] = 0
ans_array = np.zeros(N)
tsuro = deque(tsuro.tolist())
counts = 0
success_flag = False
while tsuro:
    if counts > 3 * N:
        break
    room_a, room_b = tsuro.popleft()
    room_a, room_b = room_a - 1, room_b - 1
    if depth_array[room_a] != -1 and depth_array[room_b] != -1:
        continue
    elif depth_array[room_a] != -1:
        depth_array[room_b] = depth_array[room_a] + 1
        ans_array[room_b] = room_a + 1
    elif depth_array[room_b] != -1:
        depth_array[room_a] = depth_array[room_b] + 1
        ans_array[room_a] = room_b + 1
    else:
        tsuro.append([room_a + 1, room_b + 1])
    counts += 1
if -1 not in depth_array:
    print('Yes')
    for ans in ans_array[1:]:
        print(int(ans))
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from collections import deque

import numpy as np

N, M = list(map(int, input().split()))
tsuro = [list(map(int, input().split())) for _ in range(M)]
tsuro = np.array(tsuro)
arr = list(range(2, N + 1))
tsuro = np.sort(tsuro, axis=1)
order = np.argsort(tsuro[:, 0])
tsuro = tsuro[order]

depth_array = np.ones(N) * -1
depth_array[0] = 0
ans_array = np.zeros(N)
tsuro = deque(tsuro.tolist())
counts = 0
success_flag = False
while tsuro:
    if counts > 3 * N:
        print('No')
        break
    room_a, room_b = tsuro.popleft()
    room_a, room_b = room_a - 1, room_b - 1
    if depth_array[room_a] != -1 and depth_array[room_b] != -1:
        continue
    elif depth_array[room_a] != -1:
        depth_array[room_b] = depth_array[room_a] + 1
        ans_array[room_b] = room_a + 1
    elif depth_array[room_b] != -1:
        depth_array[room_a] = depth_array[room_b] + 1
        ans_array[room_a] = room_b + 1
    else:
        tsuro.append([room_a + 1, room_b + 1])
    counts += 1
if -1 not in depth_array:
    print('Yes')
    for ans in ans_array[1:]:
        print(int(ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

N, M = map(int, input().split())
d = deque()
ans = defaultdict(int)
pre = []

for _ in range(M):
    A, B = map(int, input().split())
    if A == 1:
        ans[B] = 1
        pre.append(B)
    elif B == 1:
        ans[A] = 1
        pre.append(A)
    else:
        d.append([A,B])


while d and pre:
    c = []
    for _ in range(len(d)):
        A, B = d.popleft()
        
        if A in pre:
            if not ans[B]:
                ans[B] = A
                c.append(B)
        
        elif B in pre:
            if not ans[A]:
                ans[A] = B
                c.append(A)

        else:
            d.append([A,B])
    pre = c

if len(ans) < N:
    print("No")
else:
    print("Yes")
    for i in range(2,N+1):
        print(ans[i])

Submission status: Wrong Answer

Solution code:
def dijkstra(s, n, w, cost):
    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


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

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

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

d = dijkstra(0, n, m, cost)
if float("inf") in d:
    print('No')
else:
    print('Yes')
    for i in range(1, n):
        print(d[i])

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
graph = {}
for i in range(M):
	A,B = map(int,input().split())
	try:
		graph[A].append(B)
	except KeyError:
		graph[A] = [B]
	try:
		graph[B].append(A)
	except KeyError:
		graph[B] = [A]

stack = [1]
distance = [pow(10,9) for i in range(N+1)]
distance[1] = 0
visited = [False for x in range(N+1)]
ans = [None for i in range(N+1)]
while len(stack) > 0:
	cur = stack.pop()
	if visited[cur]:
		continue
	for v in graph[cur]:
		if distance[v] > distance[cur] + 1:
			distance[v] = distance[cur] + 1
			ans[v] = cur
		if not visited[v]:
			stack.append(v)
	visited[cur] = True

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

Submission status: Wrong Answer

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

n,m=map(int,input().split())  #頂点数n 辺の数m
edge=np.array([[int(i)for i in input().split()]+[1] for _ in range(m)],dtype=np.int64).T
graph=csr_matrix(((edge[2],edge[:2]-1)),(n,n))

#False->無向グラフ True->有効グラフ indives->スタートノード-1　return_predecessors=Trueを追加すると経路もでる
_,ans=dijkstra(graph,directed=False,indices=0,return_predecessors=True)

ans=ans[1:]+1
if -9999+1 in ans:
    print("No")
else:
    print("Yes")
    print('\n'.join(map(str,ans)))

Submission status: Wrong Answer

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append([a,b])

# program
Edict = [[] for n in range(N+1)]
for e in E:
    print(Edict)
    Edict[e[0]].append(e[1])
    Edict[e[1]].append(e[0])

output = [0] + [0] + [BigM]*(N-1)
prev = set([])
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    prev.add(n)
    elist = []
    for next in Edict[n]:
        if next not in now:
            if next not in prev:
                output[next] = n
                now.append(next)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import queue
n,m=map(int,input().split())
A=[]
B=[]
c=[0]*(n+1)
for _ in range(m):
    a,b=map(int,input().split())
    A.append(a)
    B.append(b)
q=queue.Queue()
q.put(1)
count=n-1
while not q.empty() and count>0:
    aa=q.get()
    for i in range(m):
        if A[i]==aa:
            if c[B[i]]==0:
                c[B[i]]=aa
                count-=1
                q.put(B[i])
                B[i]=-1
        elif B[i]==aa:
            if c[A[i]]==0:
                c[A[i]]=aa
                count-=1
                q.put(A[i])
                A[i]=-1
print('Yes')
for i in range(2,n+1):
    print(c[i])

Submission status: Wrong Answer

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

queue = [1]
check = [1]
next_queue = []
ans = [0 for i in range(N)]
ans[0] = 'Yes'

while(1):
    for i in queue:
        for j in [k for k, x in enumerate(A) if x == i]:
            if B[j] not in check:
                check.append(B[j])
                next_queue = [B[j]]
                ans[B[j]-1] = A[j]
    for i in queue:
        for j in [k for k, x in enumerate(B) if x == i]:
            if A[j] not in check:
                check.append(A[j])
                next_queue = [A[j]]
                ans[A[j]-1] = B[j]
    queue = next_queue
    if len(check) == N:
        break
    
for i in range(N):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append(set([a,b]))

output = [0] + [0] + [BigM]*(N-1)
prev = set([])
prev_cnt = 0
now = [1]

while len(now) > 0:
    print(E)
    print(now)
    n = now.pop(0)
    print("n=",n)
    prev_cnt += 1
    prev.add(n)
    elist = []
    for e in E:
        if n in e:
            elist.append(e)
    for e in elist:
        next = list(e - set([n]))[0]
        if next not in now:
            if next not in prev:
                output[next] = n
                now.append(next)
                E.remove(e)
    print("prev",prev)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
# from math import factorial,sqrt,ceil #,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from bisect import bisect_left
# from heapq import heappush,heappop
# from numba import njit,jit
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from fractions import gcd

# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
from networkx import Graph,shortest_path,single_source_shortest_path
G = Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
N,M = map(int,input().split())
rows = [list(map(int,input().split())) for _ in range(M)]

G.add_edges_from(rows)

# shortestPath = shortest_path(G,target=1)
shortestPath = single_source_shortest_path(G,source=1)
# shortestPath = single_target_shortest_path(G,target=1)
# shortestPathLength,shortestPath = single_source_dijkstra(G,source=1)

print(shortestPath)
if len(shortestPath) != N:
    print("No")
    exit()

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


# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Wrong Answer

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

routes = []
for i in range(m):
    x,y = map(int, input().split())
    routes.append([x-1,y-1])
    # routes[i] = routes[i] - [1,1] #道の番号をずらす

rooms = [0 for i in range(n)] # 行ったら1,まだなら0
marks = rooms # 部屋におく道標
rooms_rate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1

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


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

else:
    print('No')

Submission status: Wrong Answer

Solution code:
# abc168 D
from collections import deque

def bfs(graph, N, start):
    visited = [-1] * N
    visited[start] = 0
    que = deque([start])
    while que:
        node = que.popleft()
        for n in graph[node]:
            if visited[n] == -1:
                visited[n] = node
                que.append(n)
    print(visited)
    return visited


## ----main
N, M = list(map(int,input().split()))
graph = [[] for _ in range(N)]

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

visited = bfs(graph,N,0)

if -1 not in visited[1:]:
    print("Yes")
    for v in visited[1:]:
        print(v+1)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
print("Yes")
N, M = map(int, input().split())
path = [[] for _ in range(N)]
ind = [0 for _ in range(N)]
lis = set()
for o in range(N):
    lis.add(o)
for i in range(M):
    A, B = map(int, input().split())
    path[A-1].append(B-1)
    path[B-1].append(A-1)
que = path[0]
for p in que:
    lis.discard(p)
for l in que:
    U = lis & set(path[l])
    for m in U:
        ind[m] = l
        lis.discard(m)
    que = U
    if lis == {}:
        break
for z in range(1,N):
    ind[z] += 1
    print(ind[z])

Submission status: Wrong Answer

Solution code:
print("Yes")
N, M = map(int, input().split())
#dist = [float('inf') for _ in range(N)] 
path = [[] for _ in range(N)]
ind = [0 for _ in range(N)]
lis = set()
for o in range(N):
    lis.add(o)
for i in range(M):
    A, B = map(int, input().split())
    path[A-1].append(B-1)
    path[B-1].append(A-1)
que = path[0]
for p in que:
    lis.discard(p)
for l in que:
    U = lis & set(path[l])
    for m in U:
        ind[m] = l
        lis.discard(m)
    que = U
    if lis == {}:
        break
for z in range(1,N):
    ind[z] += 1
    print(ind[z])

Submission status: Wrong Answer

Solution code:
from heapq import heappop, heappush
n,m = map(int,input().split())
G = [[] for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
dist = [float("inf")]*n
seen = [False]*n
ans = [0]*n
def f(s):
    PQ = [(0,s)]
    dist[s] = 0
    while PQ:
        u,md = heappop(PQ)
        seen[u] = True
        if dist[u] < md: continue
        for v in G[u]:
            if seen[v]: continue
            if dist[v] > md+1:
                dist[v] = md+1
                heappush(PQ,(dist[v],v))
                ans[v] = u+1
f(0)
print("Yes")
for i in range(1,n): print(ans[i])

Submission status: Wrong Answer

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append(set([a,b]))

output = [0] + [0] + [BigM]*(N-1)
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    print("n=",n)
    prev_cnt += 1
    elist = []
    for e in E:
        if n in e:
            elist.append(e)
    for e in elist:
        next = list(e - set([n]))[0]
        if output[next] == BigM:
            output[next] = n
            now.append(int(next))
            E.remove(e)
            print(E)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
# abc168 D
from collections import deque

def bfs(graph, N, start):
    visited = [0] * N
    visited[start] = 1 # 開始点
    que = deque([start])
    while que:
        node = que.popleft()
        for n in graph[node]:
            if not visited[n]:
                visited[n] = node
                que.append(n)
    return visited


## ----main
N, M = list(map(int,input().split()))
graph = [[] for _ in range(N)]

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

visited = bfs(graph,N,0)

if all(visited[1:]):
    print("Yes")
    for v in visited[1:]:
        print(v+1)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import queue
INF = float('inf')

def bfs():
    q = queue.Queue()
    [q.put([x, 0]) for x in graph[0]]
    while not q.empty():
        n = q.get()
        nex = n[0]; now = n[1]
        if visited[nex] == INF:
            visited[nex] = now
            [q.put([x, nex]) for x in graph[nex]]
    return

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

visited = [INF for _ in range(N)]
bfs()

if INF in visited:
    print('No')
else:
    for i in range(1, N):
        print(visited[i]+1)

Submission status: Wrong Answer

Solution code:
from collections import deque

class Node:
    def __init__(self, data):
        self.data = data
        self.children = []

def main():
    N, M = map(int, input().split())
    dic = {}
    for i in range(1, N + 1):
        dic[i] = Node(i)
    for i in range(0, M):
        A, B = map(int, input().split())
        dic[A].children.append(dic[B])
        dic[B].children.append(dic[A])

    answerDic = {}
    q = deque()
    q.append(dic[1])
    while len(q) > 0:
        current = q.pop()
        for child in current.children:
            if child.data not in answerDic.keys() :
                answerDic[child.data] = current.data
                q.append(child)

    print('Yes')
    for key in range(2, N + 1):
        print(answerDic[key])

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M = map(int, input().split())
AB = [map(int, input().split()) for _ in range(M)]
A, B = [list(i) for i in zip(*AB)]

reach = [[] for i in range(N+1)]
reach[0].append(1)

for i in range(M):
    reach[A[i]].append(B[i])
    reach[B[i]].append(A[i])

d = deque()
visited = [-1]*(N+1)
ans = [-1]*(N+1)

d.appendleft(1)
visited[1] = 0

while d:
    now = d.pop()
    nexts = reach[now]

    for next in nexts:
        if visited[next] == -1:
            visited[next] = visited[now] + 1
            ans[next] = now
            d.append(next)

print('Yes')
for v in ans[2:]:
    print(v)

Submission status: Wrong Answer

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append(set([a,b]))

output = [0] + [0] + [BigM]*(N-1)
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    for e in E:
        if n in e:
            next = list(e - set([n]))[0]
            if output[next] == BigM:
                output[next] = n
                now.append(int(next))
                E.remove(e)
                print(E)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M = map(int, input().split())
AB = [map(int, input().split()) for _ in range(M)]
A, B = [list(i) for i in zip(*AB)]

reach = [[] for i in range(N+1)]
reach[0].append(1)

for i in range(M):
    reach[A[i]].append(B[i])
    reach[B[i]].append(A[i])

d = deque()
visited = [-1]*(N+1)
ans = [-1]*(N+1)

d.appendleft(1)
visited[1] = 0

while d:
    now = d.pop()
    nexts = reach[now]

    for next in nexts:
        if visited[next] == -1:
            visited[next] = visited[now] + 1
            ans[next] = now
            d.append(next)

for v in ans[2:]:
    print(v)

Submission status: Wrong Answer

Solution code:
from collections import deque

class Node:
    def __init__(self, data):
        self.data = data
        self.children = []

def main():
    N, M = map(int, input().split())
    dic = {}
    for i in range(1, N + 1):
        dic[i] = Node(i)
    for i in range(0, M):
        A, B = map(int, input().split())
        dic[A].children.append(dic[B])
        dic[B].children.append(dic[A])

    answerDic = {}
    q = deque()
    q.append(dic[1])
    while len(q) > 0:
        current = q.pop()
        for child in current.children:
            if not child.data in answerDic.keys() :
                answerDic[child.data] = current.data
                q.append(child)

    print('Yes')
    for key in range(2, N + 1):
        print(answerDic[key])

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[0 for k in range(N)]
visited[0]=1
count = 0
not_used = [k for k in range(M)]
for j in range(M-1):
    for visit in nextvisit[j]:
        """
        print("L=",L)
        print("next=",nextvisit[j])
        print("not_used", not_used)
        """
        erase = []
        for k in not_used:
            if visit == L[k][1]:
                if visited[L[k][0]-1] == 0:
                    nextvisit[j+1].append(L[k][0])
                    visited[L[k][1]-1] = 1
                    visited[L[k][0]-1] = 1
                    room[L[k][0]-1] = L[k][1]
                erase.append(k)
                
            if visit == L[k][0]:
                if visited[L[k][1]-1] == 0:
                    nextvisit[j+1].append(L[k][1])
                    visited[L[k][0]-1] = 1
                    visited[L[k][1]-1] = 1
                    room[L[k][1]-1] = L[k][0]  
                erase.append(k)
                
        not_used = list(set(not_used)-set(erase))
    
    if len(not_used) == 0:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==1:
    print(1)

Submission status: Wrong Answer

Solution code:
def bfs(graph, start, rooms):
    queue = []
    visited = [False]*rooms
    visited[start] = True
    marking = [0]*rooms
    queue.append(start)
    while queue:
        nodes = queue.pop()
        for node in graph[nodes]:
            if not visited[node]:
                visited[node] = True
                queue.append(node)
                marking[node] = nodes + 1
    return marking, visited

if __name__=="__main__":
    N, M = map(int, input().split())
    graph = [[] for i in range(N)]
    for i in range(M):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append(b)
        graph[b].append(a)

    marking, visited = bfs(graph, 0, N)

    if all(visited):
        print("Yes")
        for i in range(1, N):
            print(marking[i])
    else:
        print("No")

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[1]
count = 0
not_used = [k for k in range(M)]
for j in range(M-1):
    for visit in nextvisit[j]:
        """
        print("L=",L)
        print("next=",nextvisit[j])
        print("not_used", not_used)
        """
        erase = []
        for k in not_used:
            if visit == L[k][1]:
                if (L[k][0] not in visited):
                    nextvisit[j+1].append(L[k][0])
                    visited.append(L[k][1])
                    visited.append(L[k][0])
                    room[L[k][0]-1] = L[k][1]
                    
                erase.append(k)
                
            if visit == L[k][0]:
                if (L[k][1] not in visited):
                    nextvisit[j+1].append(L[k][1])
                    visited.append(L[k][0])
                    visited.append(L[k][1])
                    room[L[k][1]-1] = L[k][0]
                    
                erase.append(k)
                
        not_used = list(set(not_used)-set(erase))
    
    if len(not_used) == 0:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==1:
    print(1)

Submission status: Wrong Answer

Solution code:
# d
import numpy as np
n, m = [int(i) for i in input().split()]
a = [0]*m
b = [0]*m
ans = [0]*(n)
for i in range(m):
    a[i], b[i] = [int(j)-1 for j in input().split()]
    if a[i] == 0:# and ans[b[i]] == 0:
        ans[b[i]] = 1
    elif b[i] == 0:# and ans[a[i]] == 0:
        ans[a[i]] =1
# ここまででansの要素（部屋番号）には1と繋がれている部屋の案内が1となっている．
# print(ans)
# 1に直接繋がれている部屋(ans=1となっている要素番号)と接続されている部屋はそこへの案内を出す．(二回移動)
for i in range(m):
    if ans[a[i]] == 1:
        if ans[b[i]] == 0:
            ans[b[i]] = a[i]+1 # もし片方の部屋の案内板が1ならば，もう片方の部屋の案内は，その部屋にするべき．（すでに1の案内板を）
    elif ans[b[i]] == 1:
        if ans[a[i]] == 0:
            ans[a[i]] = b[i]+1 # もし片方の部屋の案内板が1ならば，もう片方の部屋の案内は，その部屋にするべき．（すでに1の案内板を）

# 三回移動
            
ans_np = np.array(ans)

if np.any(ans_np[1:] == 0):
    flag = 0
else:
    flag = 1
    
if flag == 0:
    print('No')
elif flag == 1:
    print('Yes')
    for i in range(1, n):
        print(ans[i])