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:
import sys
import copy
from io import StringIO
import unittest
import queue

def resolve():
    n, m = map(int, input().split())
    roots = [list(map(int, input().split())) for i in range(m)]

    que = queue.Queue()

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [999999 for i in range(n+1)]

    best_signs = [0 for i in range(n+1)]

    # 調べ終えた道を格納するリスト
    searched = []

    # 初期値を代入
    que.put(1)  # スタート地点
    deeps[1] = 0 # スタート地点の深さは0

    # BFS開始
    while not que.empty():

        now = que.get()

        # 繋がる道を全て確認
        for cnt, root in enumerate(roots):
            # 現在地と繋がらない道の場合・・何もしない
            if now not in root:
                continue

            # 調査済みの道の場合・・何もしない
            if str(root[0]) + "-" + str(root[1]) in searched:
                continue

            # 現在地と繋がる道の場合・・
            # [前処理]
            # 自分の座標を削除 = これで、繋がり先だけを保持した変数を作れる。
            work = copy.deepcopy(root)
            work.remove(now)
            target = work[0]

            ## 調査済みリストに追加
            #searched.append(str(root[0]) + "-" + str(root[1]))

            del roots[cnt]

            # [主処理]
            # queに追加
            que.put(target)

            # 見つけた組み合わせが最適解の場合
            if deeps[target] > deeps[now]+1:
                # 最適解を採用
                deeps[target] = deeps[now]+1
                best_signs[target] = now
            # 最小の深さを採用
            # deeps[target] = min(deeps[target], deeps[now] + 1)

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    del best_signs[0:2]

    ans = "Yes"
    for best_sign in best_signs:
        ans = ans + "\n" + str(best_sign)

    print(ans)



class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """4 4
1 2
2 3
3 4
4 2"""
        output = """Yes
1
2
2"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6"""
        output = """Yes
6
5
5
1
1"""
        self.assertIO(input, output)

if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
n,m = map(int,input().split())
Map = [[]for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    Map[a-1].append(b-1)
    Map[b-1].append(a-1)


Visited = [False for i in range(n)]
depth = [0 for i in range(n)]
q = deque()
q.append(0)
while q:
    st = q.popleft()
    for i in Map[st]:
        if Visited[i]==True:
            continue
        depth[i] = depth[st]+1
        Visited[i] = True
        q.append(i)
ans = []
depth[0] = 0
for i in range(1,n):
    for j in Map[i]:
        print(j)
        if depth[i]-1==depth[j]:
            ans.append(j+1)
            break

if len(ans)==0:
    print('No')
else:
    print('Yes')
    for i in ans:
        print(i)

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
n,m = map(int,input().split())
Map = [[]for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    Map[a-1].append(b-1)
    Map[b-1].append(a-1)


Visited = [False for i in range(n)]
depth = [0 for i in range(n)]
q = deque()
q.append(0)
while q:
    st = q.popleft()
    for i in Map[st]:
        if Visited[i]==True:
            continue
        depth[i] = depth[st]+1
        Visited[i] = True
        q.append(i)
for i in range(1,n):
    print(depth[i])

Submission status: Wrong Answer

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

n, m = [int(x) for x in input().split()] 
g = [[] for _ in range(n)] 

for _ in range(m):
    a, b = [int(x) for x in input().split()]
    g[a-1].append(b-1)
    g[b-1].append(a-1)

from collections import deque

def bfs(u):
    queue = deque([u])
    d = [None] * n 
    d[u] = 0 
    while queue:
        v = queue.popleft()
        for i in g[v]:
            if d[i] is None:
                d[i] = d[v] + 1
                queue.append(i)
                g[i].remove(v)
                
    return d

d = bfs(0)
if all([i != None for i in d]):
    print("Yes")
    for i in range(1,n):
        print(d[i])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    N, M, *AB = map(int, open(0).read().split())
    C = {}
    for i in range(M):
        a = AB[2 * i + 0] - 1
        b = AB[2 * i + 1] - 1
        if a not in C:
            C[a] = []
        C[a].append(b)
        if b not in C:
            C[b] = []
        C[b].append(a)
    ANS = {i:-1 for i in range(N)}
    D = deque()
    D.append((0, C[0]))
    print(D)
    while len(D) != 0:
        d = D.popleft()
        v = d[0]
        L = d[1]
        for l in L:
            if ANS[l] == -1:
                ANS[l] = v
                D.append((l, C[l]))
    print('Yes')
    for i in range(1, N):
        print(ANS[i] + 1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
N,M = map(int, sys.stdin.readline().split())
AB = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
edge = [[] for _ in range(N)]
for ab in AB:
    #print(ab)
    edge[ab[0]-1] +=[ab[1]-1]
    edge[ab[1]-1] +=[ab[0]-1]
#print(edge)
#深さを測る
L = [-1 for _ in range(N)]
def bfs(p, queue=[]):
    queue = [p]
    L[p]=0
    while queue:
        now = queue.pop(0)
        for ch in edge[now]:
            #print(ch)
            if L[ch] ==-1:
                L[ch] = L[now]+1
                queue.append(ch)
     


bfs(0)
print('Yes')
for i in L[1:]:
    print(i)

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=map(int,input().split())
ab=[list(map(int,input().split())) for i in range(M)]
l=[0]*N
que=deque([])
que.append(1)
def bfs():
  while que:
     if 0 not in l:
         exit()
     p=que.popleft
     for i in range(M):
          if ab[i][0]==p:
            que.append(ab[i][1])
            l[ab[i][1]-1]=p
          if ab[i][1]==p:
             que.append(ab[i][0])
             l[ab[i][0]-1]=p
  print("Yes")
  print(*l)

Submission status: Wrong Answer

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

list = [0] * (N+1)

saitan = [1]
for _ in range(M):
    next = []
    for i in range(len(AB)):
        if AB[i][0] in saitan:
            if list[AB[i][1]] == 0:
                list[AB[i][1]] = AB[i][0]
                next.append(AB[i][1])
        if AB[i][1] in saitan:
            if list[AB[i][0]] == 0:
                list[AB[i][0]] = AB[i][1]
                next.append(AB[i][0])
    saitan.extend(next)


print("YES")
for ele in list[2:]:
    print(ele)

Submission status: Wrong Answer

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

list = [0] * (N+1)

print(AB)
print(list)

saitan = [1]
for _ in range(M):
    next = []
    for i in range(len(AB)):
        if AB[i][0] in saitan:
            if list[AB[i][1]] == 0:
                list[AB[i][1]] = AB[i][0]
                next.append(AB[i][1])
        if AB[i][1] in saitan:
            if list[AB[i][0]] == 0:
                list[AB[i][0]] = AB[i][1]
                next.append(AB[i][0])
    saitan.extend(next)


print("YES")
for ele in list[2:]:
    print(ele)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

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

dist = [-1] * (n+1)
dist[0] = 0
dist[1] = 0

d = deque()
d.append(1)

while d:
 v = d.popleft()
 for i in graph[v]:
   if dist[i] != -1:
     continue
   dist[i] = dist[v] + 1
   d.append(i)

ans = dist[2:]
if len(ans) > 0:
    print('Yes')
    print(*ans, sep="\n")
else:
    print('No')

Submission status: Wrong Answer

Solution code:
def main():
    input1 = input()
    input1 = input1.split()
    N = int(input1[0])
    M = int(input1[1])

    aisle = {}
    result = [0]*(N-1)
    record = [1]
    count = N-1
    in1 = 0
    in2 = 0

    for i in range(M):
        input2 = input()
        input2 = input2.split()
        in1 = int(input2[0])
        in2 = int(input2[1])
        aisle.setdefault(in1,[]).append(in2)
        aisle.setdefault(in2,[]).append(in1)

    while count != 0 and len(record) != 0:
        pop1 = record.pop(0)
        if pop1 in aisle:
            for i in aisle[pop1]:
                if result[i-2] == 0:
                    result[i-2] = pop1
                    record.append(i)
                    count = count -1
        else:
            break

    if count == 0:
        print("Yes")
        for i in range(len(result)):
            print(result[i])
    else:
        print("No")


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    input1 = input()
    input1 = input1.split()
    N = int(input1[0])
    M = int(input1[1])

    aisle = {}
    result = [0]*(N-1)
    record = [1]
    count = N-1
    in1 = 0
    in2 = 0

    for i in range(M):
        input2 = input()
        input2 = input2.split()
        in1 = int(input2[0])
        in2 = int(input2[1])
        aisle.setdefault(in1,[]).append(in2)
        aisle.setdefault(in2,[]).append(in1)

    while count != 0 and len(record) != 0:
        pop1 = record.pop(0)
        if pop1 in aisle:
            for i in aisle[pop1]:
                if result[i-2] == 0:
                    result[i-2] = pop1
                    record.append(i)
                    count = count -1

    if count == 0:
        print("Yes")
        for i in range(len(result)):
            print(result[i])
    else:
        print("No")


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

loads = [[] for _ in range(N+1)]

for AB in ABs:
    loads[AB[0]].append(AB[1])
    loads[AB[1]].append(AB[0])


dq = collections.deque()

dq.append(1)
ans_list = [0 for _ in range(N+1)]

#print(loads)
print("Yes")
for load in loads[1:]:
    i = dq.popleft()

    for vec in load:
#        print(vec)
        if(ans_list[vec] == 0):
            ans_list[vec] = loads.index(load)
            dq.append(vec)
#        print(ans_list)
#        print(dq)

    if(len(dq) == 0):
        break

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

Submission status: Wrong Answer

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

p = np.zeros(n+1,dtype=int)
s = np.zeros(n+1,dtype=int)

s[1]=1

a = np.zeros(m,dtype=int)
b = np.zeros(m,dtype=int)


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

for i in range(1,n+1):
    t=False
    for j in range(1,n+1):
        if s[j] == i:
            for k in range(m):
                if a[k]==j and p[ b[k] ] == 0:
                    p[b[k]]=a[k]
                    s[b[k]]=j+1
                    t=True

                if b[k]==j and p[a[k]]==0:
                    p[a[k]]=b[k]
                    s[a[k]]=j+1
                    t=True
    if t==False:
        break
    
if 0 in p[2:]:
    print('No')
else:
    print('Yes')
    for q in p[2:]:
        print(q)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
N, M = LI()
AB = [LI() for _ in range(M)]
path = [[] for _ in range(N+1)]
mp = []
ans = [0] * (N+1)

for ab in AB:
	a = ab[0]
	b = ab[1]
	path[a].append(b)
	path[b].append(a)
	#print(a,b)

def bfs(tree, st, endlist, endnum):
	queue = collections.deque()
	queue.append([-1,st])
	endlist[st] -= 1
	now = [-1,-1,-1]
	pre = []
	depth = 0
	histind = -1
	node = -1
	hist = []
	res = []
	allres = []
	while queue:
		pre = now[:]
		now = queue.popleft()
		histind = now[0]
		node = now[1]
		hist.append([histind,node])
		#来たときは絶対に初回
		res = [node,hist[histind][1]]
		allres.append(res[::])
		endnum -= 1
		if endnum == 0:
			return allres
		for v in path[node]:
			if endlist[v] > 0:
				queue.append([len(hist)-1,v])
				#endlist更新
				endlist[v] -= 1
		continue
	return None

#print_map(path)
result = bfs(path, 1, [1] * (N+1), N)
print("[TO, FROM] = {0}".format(result))
if result is None:
	print("No")
	exit(0)
print("Yes")
execnum = N
maxlen = len(result[len(result)-1])
for i in result:
	print(i)
	if ans[i[0]] == 0:
		ans[i[0]] = i[1]
		execnum-=1
		if execnum == 0:
			break

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

Submission status: Wrong Answer

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

ans_list = [0] * (N+1)

dq = collections.deque()

dq.append(1)

for hoge in range(500000):
    i = dq.popleft()
    iList = [temp for temp in ABs if i in temp]

    iList = list(itertools.chain.from_iterable(iList))
    iList = [temp for temp in iList if iList !=i]

    for hoge in iList:
        if(ans_list[hoge] == 0):
            ans_list[hoge] = i
        dq.append(hoge)

    if(0 not in ans_list[2:]):
        break

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

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
N, M = LI()
AB = [LI() for _ in range(M)]
path = [[] for _ in range(N+1)]
mp = []
ans = [0] * (N+1)

for ab in AB:
	a = ab[0]
	b = ab[1]
	path[a].append(b)
	path[b].append(a)
	#print(a,b)

def bfs(tree, st, endlist, endnum):
	queue = collections.deque()
	queue.append([-1,st])
	endlist[st] -= 1
	now = [-1,-1,-1]
	pre = []
	depth = 0
	histind = -1
	node = -1
	hist = []
	res = []
	allres = []
	while queue:
		pre = now[:]
		now = queue.popleft()
		histind = now[0]
		node = now[1]
		hist.append([histind,node])
		#来たときは絶対に初回
		res = [node,hist[histind][1]]
		allres.append(res[::])
		endnum -= 1
		if endnum == 0:
			return allres
		for v in path[node]:
			if endlist[v] > 0:
				queue.append([len(hist)-1,v])
				#endlist更新
				endlist[v] -= 1
		continue
	return None

#print_map(path)
result = bfs(path, 1, [1] * (N+1), N)
#print(result)
if result is None:
	print("No")
	exit(0)
print("Yes")
execnum = N-1
maxlen = len(result[len(result)-1])
for i in result:
	if ans[i[0]] == 0:
		ans[i[0]] = i[1]
		execnum-=1
		if execnum == 0:
			break

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

Submission status: Wrong Answer

Solution code:
import numpy as np

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

Submission status: Wrong Answer

Solution code:
from collections import deque

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

res = {}
for i in range(m):
    a,b = map(int,input().split())
    res.setdefault(a,[]).append(b)
    res.setdefault(b,[]).append(a)

dist =[0] * (n+1)
sirusi = [0] * (n+1)
dist[1] = -1

que = deque([])
ique = deque([])
x = res.pop(1)
#print(x)
que.append(x)
ique.append(1)

d = 1
#print(len(que))

while(len(que)>0):
    data = que.popleft()
    index = ique.popleft()
    #print(data)
    ind = 0
    for i in data:
        #print(int(i))

        if dist[int(i)] == 0 :
            # print("d")
            # print(index)
            dist[i] = d
            sirusi[i] = index
            que.append(res.pop(i))
            ique.append(int(i))
        ind += 1
    d = d + 1
#
# while(len(next) > 0):
#     data = next.pop()
#     print("data = ",end="")
#     print(data)
#     if(not(type(data) is int)):
#         print("not int")
#         for i in range(len(data)):
#             if dist[i]  != 0:
#                 dist[data[i]] = d
#                 print("res[data[i]] = ")
#                 #print(res[data[i]])
#                 next.append(res.pop(data[i]))
#     else:
#         print("int")
#         if dist[data] == 0:
#             dist[data] = d
#             print("res = ",end="")
#             print(res[data])
#             next.append(res[data])
#
#     d = d +1



#print(dist)
#print(sirusi)
print("YES")
for i in range(2,len(sirusi)):
    print(sirusi[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

res = {}
for i in range(m):
    a,b = map(int,input().split())
    res.setdefault(a,[]).append(b)
    res.setdefault(b,[]).append(a)

dist =[0] * (n+1)
sirusi = [0] * (n+1)
dist[1] = -1

que = deque([])
ique = deque([])
x = res.pop(1)
#print(x)
que.append(x)
ique.append(1)

d = 1
#print(len(que))

while(len(que)>0):
    data = que.popleft()
    index = ique.popleft()
    #print(data)
    ind = 0
    for i in data:
        #print(int(i))

        if dist[int(i)] == 0 :
            # print("d")
            # print(index)
            dist[i] = d
            sirusi[i] = index
            que.append(res.pop(i))
            ique.append(int(i))
        ind += 1
    d = d + 1
#
# while(len(next) > 0):
#     data = next.pop()
#     print("data = ",end="")
#     print(data)
#     if(not(type(data) is int)):
#         print("not int")
#         for i in range(len(data)):
#             if dist[i]  != 0:
#                 dist[data[i]] = d
#                 print("res[data[i]] = ")
#                 #print(res[data[i]])
#                 next.append(res.pop(data[i]))
#     else:
#         print("int")
#         if dist[data] == 0:
#             dist[data] = d
#             print("res = ",end="")
#             print(res[data])
#             next.append(res[data])
#
#     d = d +1



#print(dist)
#print(sirusi)
for i in range(2,len(sirusi)):
    print(sirusi[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

res = {}
for i in range(m):
    a,b = map(int,input().split())
    res.setdefault(a,[]).append(b)
    res.setdefault(b,[]).append(a)

dist =[0] * (n+1)
sirusi = [0] * (n+1)
dist[1] = -1

que = deque([])
ique = deque([])
x = res.pop(1)
#print(x)
que.append(x)
ique.append(1)

d = 1
#print(len(que))

while(len(que)>0):
    data = que.popleft()
    index = ique.popleft()
    #print(data)
    ind = 0
    for i in data:
        #print(int(i))

        if dist[int(i)] == 0 :
            # print("d")
            # print(index)
            dist[i] = d
            sirusi[i] = index
            que.append(res.pop(i))
            ique.append(int(i))
        ind += 1
    d = d + 1
#
# while(len(next) > 0):
#     data = next.pop()
#     print("data = ",end="")
#     print(data)
#     if(not(type(data) is int)):
#         print("not int")
#         for i in range(len(data)):
#             if dist[i]  != 0:
#                 dist[data[i]] = d
#                 print("res[data[i]] = ")
#                 #print(res[data[i]])
#                 next.append(res.pop(data[i]))
#     else:
#         print("int")
#         if dist[data] == 0:
#             dist[data] = d
#             print("res = ",end="")
#             print(res[data])
#             next.append(res[data])
#
#     d = d +1



#print(dist)
#print(sirusi)
for i in sirusi:
    print(i)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
N, M = LI()
AB = [LI() for _ in range(M)]
path = [[] for _ in range(N+1)]
mp = []
ans = [0] * (N+1)

for ab in AB:
	a = ab[0]
	b = ab[1]
	path[a].append(b)
	path[b].append(a)
	#print(a,b)

def bfs(tree, st, endlist, endnum):
	queue = collections.deque()
	queue.append([-1,st])
	endlist[st] -= 1
	now = [-1,-1,-1]
	pre = []
	depth = 0
	histind = -1
	node = -1
	hist = []
	res = []
	allres = []
	while queue:
		pre = now[:]
		now = queue.popleft()
		histind = now[0]
		node = now[1]
		hist.append([histind,node])
		#来たときは絶対に初回
		res = [node]
		ident = histind
		while res[len(res)-1]!=1:
			res.append(hist[ident][1])
			ident = hist[ident][0]
		allres.append(res[::-1])
		endnum -= 1
		if endnum == 0:
			return allres
		for v in path[node]:
			if endlist[v] > 0:
				queue.append([len(hist)-1,v])
				#endlist更新
				endlist[v] -= 1
		continue
	return None

#print_map(path)
result = bfs(path, 1, [1] * (N+1), N)
#print(result)
if result is None:
	print("No")
	exit(0)
print("Yes")
maxlen = len(result[len(result)-1])
for i in result[::-1]:
	if len(i) < maxlen:
		break
	for ind,v in enumerate(i[::-1]):
		if v == 1:
			break
		if ans[v] == 0:
			ans[v] = i[len(i)-2-ind]

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

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
ways = [[] for i in range(N)]
for i in range(M):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  ways[a].append(b)
  ways[b].append(a)
print(ways)
searched = [0 for i in range(N)]
searched[0] = 1
ans = [0 for i in range(N)]
d = deque([])
d.append(0)
while d:
  tmp = d.popleft()
  for w in ways[tmp]:
    if searched[w] == 0:
      searched[w] = 1
      ans[w] = tmp
      d.append(w)
print("Yes")
for a in ans[1:]:
  print(a + 1)

Submission status: Wrong Answer

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

from collections import deque

dist = [-1] * N
prev = [-1] * N
dist[0] = 0
queue = deque([0])
while queue:
    tmp = queue.popleft()
    for i in graph[tmp]:
        if dist[i] != -1:
            continue
        dist[i] = dist[tmp] + 1
        prev[i] = tmp
        queue.append(i)


print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Wrong Answer

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

print(graph)
from collections import deque

dist = [-1] * N
prev = [-1] * N
dist[0] = 0
queue = deque([0])
while queue:
    tmp = queue.popleft()
    for i in graph[tmp]:
        if dist[i] != -1:
            continue
        dist[i] = dist[tmp] + 1
        prev[i] = tmp
        queue.append(i)


for i in dist[1:]:
    print(i)

Submission status: Wrong Answer

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

n, m =  map(int, input().split()) # nは頂点の数、mは辺の数
pic = [[] for _ in range(n)] # 隣接リスト_初期化
#print(n,m)

for _ in range(m): # 隣接リスト_取り込み
    a, b = map(int, input().split())
    pic[a-1].append(b-1)
    pic[b-1].append(a-1)
#print(pic)

from collections import deque

def BFS(u): # 'u'を開始位置として各頂点までの距離を探索する関数
    queue = deque([u]) # dequeオブジェクトとして初期化、初期値は開始位置の'u'のみ
    dis = [None] * n # uからの距離を全ノード分初期化
    dis[u] = 0 # 自分'u'との距離は0
    ans = [-1] * n
    #print(ans)
    while queue:
        v = queue.popleft() # v:探索元のノード 
        for i in pic[v]: # pic[v]: 探索元のノードに隣接するノードのリスト
            if ans[i] == -1:
                ans[i] = v
            if dis[i] is None:
                dis[i] = dis[v] + 1
                queue.append(i)
    return ans

# 0からの各頂点の距離
dis = BFS(1)
print('Yes')
for j in dis[1:]:
    print(j+1)

Submission status: Wrong Answer

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

n, m =  map(int, input().split()) # nは頂点の数、mは辺の数
pic = [[] for _ in range(n)] # 隣接リスト_初期化
#print(n,m)

for _ in range(m): # 隣接リスト_取り込み
    a, b = map(int, input().split())
    pic[a-1].append(b-1)
    pic[b-1].append(a-1)
#print(pic)

from collections import deque

def BFS(u): # 'u'を開始位置として各頂点までの距離を探索する関数
    queue = deque([u]) # dequeオブジェクトとして初期化、初期値は開始位置の'u'のみ
    dis = [None] * n # uからの距離を全ノード分初期化
    dis[u] = 0 # 自分'u'との距離は0
    while queue:
        v = queue.popleft() # v:探索元のノード 
        for i in pic[v]: # pic[v]: 探索元のノードに隣接するノード
            if dis[i] is None:
                dis[i] = dis[v] + 1
                queue.append(i)
    return dis

# 0からの各頂点の距離
dis = BFS(0)
print('Yes')
for j in dis[1:]:
    print(j)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
l=[[] for i in range(n)]
for i in range(m):
  a,b=map(int,input().split())
  l[a-1].append(b)
  l[b-1].append(a)
ans=[-1]*n
x=[1]
y=[]
count=1
while count<n and len(x)>0:
  for i in x:
    for j in l[i-1]:
      if ans[j-1]==-1:
        ans[j-1]=i
        y.append(j)
        count+=1
  x=y
  y=[]
if count<n:
  print('No')
else:
  print('Yes')
  for i in range(1,n):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
l=[[] for i in range(n)]
for i in range(m):
  a,b=map(int,input().split())
  l[a-1].append(b)
  l[b-1].append(a)
ans=[-1]*n
x=[1]
y=[]
count=1
while count<n and len(x)>0:
  for i in x:
    for j in l[i-1]:
      if ans[j-1]==-1:
        ans[j-1]=i
        y.append(j)
        count+=1
  x=y
  y=[]
print(l)
if count<n:
  print('No')
else:
  print('Yes')
  for i in range(1,n):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
l=[[]]*n
for i in range(m):
  a,b=map(int,input().split())
  l[a-1].append(b)
  l[b-1].append(a)
ans=[-1]*n
x=[1]
y=[]
count=1
while count<n and len(x)>0:
  for i in x:
    for j in l[i-1]:
      if ans[j-1]==-1:
        ans[j-1]=i
        y.append(j)
        count+=1
  x=y
  y=[]
if count<n:
  print('No')
else:
  print('Yes')
  for i in range(2,n):
    print(ans[i-1])

Submission status: Wrong Answer

Solution code:
from collections import deque, defaultdict
N, M = map(int, input().split())
tree = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(lambda x: int(x)-1, input().split())
    tree[a].append(b)
    tree[b].append(a)

visited = [False]*N
q = deque([0])
visited[0] = True
ans = defaultdict(int)
while len(q):
    v = q.popleft()
    for e in tree[v]:
        if visited[e]:
            continue
        visited[e] = True
        ans[e] = v
        q.append(e)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import queue

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

guide = {}
room = defaultdict(list)

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

print(room)

q = queue.Queue()

for i in room[1]:
    q.put(i)
    guide[i] = 1

while not(q.empty()):
    x = q.get()
    for i in room[x]:
        if i not in guide:
            guide[i]=x
            q.put(i)
if len(guide) != N-1:
    print("No")
else:
    print("Yes")
    for i in range(2,N+1):
        print(guide[i])

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import queue

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

guide = {}
room = defaultdict(list)

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

print(room)

q = queue.Queue()

for i in room[1]:
    q.put(i)
    guide[i] = 1

while not(q.empty()):
    x = q.get()
    for i in room[x]:
        if i not in guide:
            guide[i]=x
            q.put(i)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import queue

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

guide = {}  #道標
room = defaultdict(list)   #各部屋に行くことができる部屋番号

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

print(room)

q = queue.Queue()

for i in room[1]:
    q.put(i)
    guide[i] = 1

while not(q.empty()):
    x = q.get()
    for i in room[x]:
        if i not in guide:
            guide[i]=x
            q.put(i)

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