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 queue

def main():
  N, M = map(int, input().split())
  routes = []
  for m in range(M):
    n1, n2 = map(int, input().split())
    routes.append([n1, n2])

  dic = {}
  for route in routes:
    n1 = route[0]
    n2 = route[1]

    dic.setdefault("{}".format(n1), []).append("{}".format(n2))
    dic.setdefault("{}".format(n2), []).append("{}".format(n1))

  q = queue.Queue()
  try:
    for i in dic["1"]:
          q.put(i)
          q.put("1")
  except:
    print("No")
    return

  michishirube = {}

  while not q.empty():
      
    dist = q.get()
    parent = q.get()
    if dist in michishirube:
      continue
    if dist == "1":
      continue
    
    michishirube[dist] = parent
    if len(michishirube) == N-1:
      break

    for i in dic[dist]:
      q.put(i)
      q.put(dist)

  if not len(michishirube) == N-1:
    print("No")
    return
  
  michishirube_sorted = dict(sorted(michishirube.items(), key=lambda x:x[0]))
  print("Yes")
  for v in michishirube_sorted.values():
    print(v)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as d, deque

def bfs(adj, start, n):
	visited = [0] * (n + 1)
	tab = [0] * n
	q = deque([start])
	visited[start] = 1
	while q:
		s = q.popleft()
		for i in adj[s]:
			if visited[i] == 0:
				q.append(i)
				visited[i] = 1
				tab[i - 1] = tab[s - 1] + 1
	return tab

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

t = bfs(adj, 1, n)
if 0 in t[1:]:
	print('No')
else:
	print('Yes')
	for i in range(1, n):
		print(adj[i+1][0])

Submission status: Wrong Answer

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

    aisle = [[0 for i in range(N)]for j in range(N)]
    result = [0]*(N-1)
    record = [0]
    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])
        if in1-1 < in2-1:
            aisle[in1-1][in2-1] = 1
        else:
            aisle[in2-1][in1-1] = 1

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

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

ikeru = []
for i in range(N):
    ikeru.append([])

answer = [-1] * (N+1)
mita = []

def tree ():
    for i in range(M):
        No = i + 1
        for j in range(M):
            if A[j] == No :
                if mita.count(B[j]) == 0:
                    ikeru[i].append(B[j])
                    mita.append(B[j])

            if B[j] == No :
                if mita.count(A[j]) == 0:
                    ikeru[i].append(A[j])
                    mita.append(A[j])

        mita.append(No)

def tansaku(hazime):
    if len(ikeru[hazime - 1]) > 0:
        for i in range(len(ikeru[hazime - 1])):
            No = hazime
            if answer[ikeru[hazime-1][i]] == -1:
                answer[ikeru[hazime-1][i]] = No
                tansaku(ikeru[hazime-1][i])

                

tree()
tansaku(1)
answer[0] = 1
answer[1] = 1
if answer.count(-1) == 0:
    print('Yes')
    for i in range(2,N+1):
        print(answer[i])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
nm=list(map(int, input().split()))
n=nm[0]
m=nm[1]
ab=[]
ans=['Yes']+[0]*(n-1)
room=[i+2 for i in range(n-1)]

for i in range(m):
    ab.append(list(map(int, input().split())))

roomto=[1]
flg=True
while flg:
    roomto1=[]
    path=[]
    flg=False
    for pair in ab:
        if pair[0] in roomto and pair[1] in room:
            roomto1.append(pair[1])
            ab.remove(pair)
            path.append(pair)
            flg=True
        elif pair[1] in roomto and pair[0] in room:
            roomto1.append(pair[0])
            ab.remove(pair)
            path.append(pair)
            flg=True
    roomto1=list(set(roomto1))
    roomto=roomto1
    for r in roomto1:
        room.remove(r)
        for pair in path:
            if r==pair[0]:
                ans[r-1]=pair[1]
            elif r==pair[1]:
                ans[r-1]=pair[0]


if 0 not in ans:
    for value in ans:
        print(value)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    N,M= map(int, input().split())
    ans = [-1]*(N+1)
    ans2 = [-1]*(N+1)
    ans[1] = 0

    L=[]
    [L.append([])for _ in range(N+1)]

    for i in range(M):
        A,B = map(int, input().split())
        L[A].append(B)
        L[B].append(A)
    
    q = deque()
    qq = deque()


    for i in range(len(L[1])):
        q.append(L[1][i])
        qq.append(0)

    while len(q) !=0:
        temp = q.popleft()
        tempq = qq.popleft()
        if ans[temp]==-1:
            ans[temp] = tempq + 1

            for i in range(len(L[temp])):
                ans2[temp]=L[temp][i]
                q.append(L[temp][i])
                qq.append(tempq + 1)

    for i in range(2,N+1):
        if ans[i]==-1:
            print('No')
            return

    print('Yes')

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





if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,m = map(int, input().split())
d = {}
for i in range(m):
  a,b = map(int, input().split())
  if a in d:
    l = d[a]
    l.append(b)
    d[a] = l
  else:
    d[a] = [b]
  if b in d:
    l = d[b]
    l.append(a)
    d[b] = l
  else:
    d[b] = [a]
clear = [1]
ans_ = [1]
ans = [0]*(n-1)
while(0 in ans):
  for i in ans_:
    ans__ = []
    for j in d[i]:
      if j in clear:
        continue
      else:
        clear.append(j)
        ans__.append(j)
        ans[j-2] = i
  ans_ = ans__
  if len(ans_) == 0:
    break
if 0 in ans:
  print("No")
else:
  print("Yes")
  for i in ans:
    print(i)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop

INT_MAX = 10 ** 9


def main():
  n, m = map(int, input().split())
  ab = (map(int, input().split()) for i in range(m))
  
  g = [[0] * (n+1) for i in range(n+1)]
  gp = [INT_MAX] * (n+1)
  gf = [0] * (n+1)
  
  for a, b in ab:
    g[a][b] = 1
    g[b][a] = 1
  
  h = [(1, 1, 0)]
  
  while h:
    a, b, p = heappop(h)
    if p < gp[a]:
      gp[a] = p
      gf[a] = b
    else:
      continue
    for z in range(1, n+1):
      if g[a][z]:
        heappush(h, (z, a, p + g[a][b]))
  
  r = gf[2:]
  print(all(0 < i < INT_MAX for i in r))
  for i in r:
    print(i)
  
  
  
if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
C = [[0 for j in range(2)] for i in range(m)]
for i in range(m):
    C[i] = list(map(int,input().split()))
    if C[i][0] > C[i][1]:
        C[i][0], C[i][1] = C[i][1],C[i][0]
sortF = lambda val : val[0]
C.sort(key=sortF)
a =  [0]*n
b = [0]*n
for i in range(m):
    if C[i][0] == 1:
        a[C[i][1]-1] = C[i][0]
        b[C[i][1]-1] += 1
    elif a[C[i][1]-1] != 0:
        a[C[i][0]-1] = C[i][1]
        b[C[i][0]-1] = b[C[i][1]-1] + 1
    elif a[C[i][0]-1] != 0:
        a[C[i][1]-1] = C[i][0]
        b[C[i][1]-1] = b[C[i][0]-1] + 1
for i in range(m):
    if a[C[i][1]-1] != 0:
        if b[C[i][1]-1] != 0 and b[C[i][1]-1] + 1 < b[C[i][0]-1]:  
            a[C[i][0]-1] = C[i][1]
            b[C[i][0]-1] = b[C[i][1]-1] + 1
    elif a[C[i][0]-1] != 0:
        if b[C[i][0]-1] != 0 and b[C[i][1]-1] + 1 < b[C[i][1]-1]:  
            a[C[i][1]-1] = C[i][0]
            b[C[i][1]-1] = b[C[i][0]-1] + 1
print("Yes")
for i in range(n-1):
    print(a[i+1])

Submission status: Wrong Answer

Solution code:
# = int(input())
N, M = map(int, input().split())
# = list(map(int, input().split()))
# = [int(input()) for i in range(N)]
AB = [list(map(int, input().split())) for i in range(M)]
sign = [0]*(N-1)
ilist=[]

for i in range(M):
    if AB[i][0] == 1:
         sign[AB[i][1]-2] = 1
         ilist.append(i)
    elif AB[i][1] == 1:
         sign[AB[i][0]-2] = 1
         ilist.append(i)
for i in range(len(ilist)):
    del AB[ilist[i]-i]
ilist = []
length = len(AB)
#print(AB)

for i in range(length):
    if sign[AB[i][0]-2] == 1 and sign[AB[i][1]-2] != 1:
        sign[AB[i][1]-2] = AB[i][0]
        ilist.append(i)
    elif sign[AB[i][1]-2] == 1 and sign[AB[i][0]-2] != 1:
        sign[AB[i][0]-2] = AB[i][1]
        ilist.append(i)
for i in range(len(ilist)):
    del AB[ilist[i]-i]
ilist = []
length = len(AB)

for i in range(10):
    for i in range(length):
        if sign[AB[i][0]-2] != 0 and sign[AB[i][1]-2] == 0:
            sign[AB[i][1]-2] = AB[i][0]
            ilist.append(i)
        elif sign[AB[i][1]-2] != 0 and sign[AB[i][0]-2] == 0:
            sign[AB[i][0]-2] = AB[i][1]
            ilist.append(i)
    for i in range(len(ilist)):
#        print(ilist)
        del AB[ilist[i]-i]
#        print(AB)
    ilist = []
    if len(AB) == length:
        break
    else:
        length = len(AB)
#        print(length)

if sign.count(0) > 0:
    print("No")
else:
    print("Yes")
    for number in sign:
        print(number)

Submission status: Wrong Answer

Solution code:
N,M = list(map(int,input().split()))
A = [list(map(int,input().split())) for _ in range(M)]
A.sort(key=lambda x: x[0],reverse = True)

floor = [10**6] * (N+1)
connect = [[] for _ in range(N+1)]
ans = [10**6] * (N+1)

floor[1] = 0

for a,b in A:
    if floor[a] < floor[b]:
        floor[b] = floor[a]+1
        ans[b] = a
    elif floor[a] > floor[b]:
        floor[a] = floor[b]+1
        ans[a] = b
    connect[a].append(b)
    connect[b].append(a)

for i in connect[1]:
    ans[i] = 1

def f(l):
    tmp = list(map(lambda x:floor[x], l))
    return tmp

print("Yes")
for i,l in enumerate(connect[2:]):
    print(l[f(l).index(min(f(l)))])

Submission status: Wrong Answer

Solution code:
import sys
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())

from collections import deque

n,m = LI()
p = [[] for i in range(n)]
r = [-1]*n
c = [-1]*n
d = deque()

for _ in range(m):
    a,b = LI()
    p[a-1].append(b-1)
    p[b-1].append(a-1)

r[0] = 0
d.append(0)
while(len(d) > 0):
    x = d.pop()
    for i in p[x]:
        if(r[i] == -1):
            r[i] = r[x] + 1
            c[i] = x
            d.append(i)


flg = True
for i in range(n):
    if(r[i] == -1):
        flg = False
        break

if(flg):
    print("Yes")
    for i in range(1,n):
        print(c[i]+1)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import math
a,b=map(int,input().split())
route_list=[]
for i   in range(a):
    route_list.extend([[0]*a])
#print(route_list)
route_list[1][1] = 1
for i in range(b):
    x,y=map(int,input().split())
#    print(route_list[x-1][y-1])
    route_list[x-1][y-1]=1
    route_list[y-1][x-1]=1
#    print(route_list)
print(route_list)
#colors = [["red", "orange"], ["blue", "green"]]
#colors[1][0] = 1
#print(colors)
#route_list = [[0, 50, 80, 0, 0], [0, 0, 20, 15, 0 ], [0, 0, 0, 10, 15], [0, 0, 0, 0, 30], [0, 0, 0, 0, 0]] # 初期のノード間の距離のリスト

node_num = len(route_list) #ノードの数

unsearched_nodes = list(range(node_num)) # 未探索ノード
distance = [math.inf] * node_num # ノードごとの距離のリスト
previous_nodes = [-1] * node_num # 最短経路でそのノードのひとつ前に到達するノードのリスト
distance[0] = 0 # 初期のノードの距離は0とする

# @GDaigo さんのコメントより関数の追加 2017/03/18
def get_target_min_index(min_index, distance, unsearched_nodes):
    start = 0
    while True:
        index = distance.index(min_index, start)
        found = index in unsearched_nodes
        if found:
            return index
        else:
            start = index + 1

while(len(unsearched_nodes) != 0): #未探索ノードがなくなるまで繰り返す
    # まず未探索ノードのうちdistanceが最小のものを選択する
    posible_min_distance = math.inf # 最小のdistanceを見つけるための一時的なdistance。初期値は inf に設定。
    for node_index in unsearched_nodes: # 未探索のノードのループ
        if posible_min_distance > distance[node_index]:
            posible_min_distance = distance[node_index] # より小さい値が見つかれば更新
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes) # 未探索ノードのうちで最小のindex番号を取得
    unsearched_nodes.remove(target_min_index) # ここで探索するので未探索リストから除去

    target_edge = route_list[target_min_index] # ターゲットになるノードからのびるエッジのリスト
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis # 過去に設定されたdistanceよりも小さい場合はdistanceを更新
                previous_nodes[index] =  target_min_index #　ひとつ前に到達するノードのリストも更新

# 以下で結果の表示
ary=[0]*(a-1)
print(ary)
for i in range(2,a+1):
    #print("-----距離-----")
    j=i-2
    v=distance[i - 1]
    if v==float('inf'):
        print("No")
        break


    #print("-----経路-----")
    previous_node = i - 1
    f=0

    while previous_node != -1:
        if previous_node !=0:

            ary[j]=previous_node + 1
            f+=1
            if f==2:
                ary[j]=previous_node + 1

            print(str(previous_node + 1) + " <- ", end='')
            i+1
        else:
            print(str(previous_node + 1))
        previous_node = previous_nodes[previous_node]
print(ary)
if len(ary)==a-1:
    print("yes")
    for i in ary:
     print(i)

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    RoomNum,PathNum=map(int,input().split())

    Link=[]

    for _ in range(PathNum):
        array=input().split()
        Link.append(list(map(int,array)))
        #Link.append(list(map(int,[array[1],array[0]])))

    Link.sort()

    room_que=deque([1])

    sign=[]
    room_num=[]

    while len(room_que)>0 and len(Link)>0:
        current_room=room_que.popleft()
        for link in Link[:]:
            if (current_room in link):
                room_que.append(link[link.index(current_room)^1])

                if (link[link.index(current_room)^1] in room_num)==False:
                    sign.append(current_room)
                    room_num.append(link[link.index(current_room)^1])
                Link.remove(link)



    if len(sign)!=RoomNum-1:
        print("No")
    else:
        RS=zip(room_num,sign)
        RS=sorted(RS)
        room_num,sign=zip(*RS)
        print("yes")
        for i in sign:
            print(i)

if __name__=="__main__":
    main()

Submission status: Wrong Answer

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

road = [[] for _ in range(N+1)]
for i in range(M):
    A, B = map(int, input().split())
    road[A].append(B)
    road[B].append(A)
# print(road)


ans = [-1] * (N + 1)
ans[1] = 0
ans[0] = 0

stack = deque([])
for r in road[1]:
    stack.append(r)


def dfs(s):
    now = s
    while len(stack) > 0:
        next_root = stack.popleft()
        # print("now ", now)
        # print("next ", next_root)

        for r in road[now]:
            if ans[r] == -1:
                stack.append(r)
                ans[r] = now

        now = next_root
        # print(ans)
        # print("stack", stack)
        # print()
dfs(1)

temp = set(ans)

print("Yes")
for a in ans[2:]:
    print(a)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
A = []
B = []
c = [0]*(n-1)
for i in range(m):
    a, b = map(int, input().split())
    if a > b:
        a, b = b, a
    if a == 1:
        c[b-2] = 1
    else:
        A.append(a)
        B.append(b)
i = 0
while len(A) > 0:
    if c[A[i]-2] != 0:
        if c[B[i]-2] != 0:
            del A[i]
            del B[i]
        else:
            c[B[i]-2] = A.pop(i)
            del B[i]
    elif c[B[i]-2] != 0:
        c[A[i]-2] = B.pop(i)
        del A[i]
    else:
        i += 1
    if i >= len(A):
        i = 0
print("Yes")
for i in range(n-1):
    print(c[i])

Submission status: Wrong Answer

Solution code:
N,M=map(int, input().split())
lt=[]
state=[0]*N
for i in range(M):
  A,B=map(int, input().split())
  lt.append([A,B])
  if(A==1):state[B-1]=1
  if(B==1):state[A-1]=1
for i in range(N):
  for k in range(M):
    if(state[lt[k][0]-1]==i+1): 
      if(state[lt[k][1]-1]==0):
        state[lt[k][1]-1]=lt[k][0]
        print(i+1)
    if(state[lt[k][1]-1]==i+1):
      if(state[lt[k][0]-1]==0):
        state[lt[k][0]-1]=lt[k][1]


if (min(state[1:])==0): print("No")
else:
  print("Yes")
  for i in range(N-1):
    print(state[i+1])

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
#import math
#import itertools
#import re
#from functools import lru_cache

input = sys.stdin.readline
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline


def main():
    n, m = list(map(int, input().split()))
    AB = [list(map(int, input().split())) for _ in range(m)]
    graph = [[] for _ in range(n)]
    for a, b in AB:
        graph[a-1].append(b)
        graph[b-1].append(a)
    dist = np.ones(n)
    dist *= -1
    dist[0] = 0
    queue = [[1]]
    while True:
        positions = queue.pop()
        for p in positions:
            queue_next = []
            for next in graph[p-1]:
                if dist[next-1] == -1:
                    dist[next-1] = p
                    queue_next.append(next)
        if len(queue_next) == 0:
            break
        queue.append(queue_next)
    if np.count_nonzero(dist == -1) > 0:
        print('No')
    else:
        print('Yes')
        for d in dist[1:]:
            print(int(d))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
n,m = map(int,input().split())
G = [set() for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    G[a-1].add(b-1)
    G[b-1].add(a-1)
ans = [-1 for _ in range(n)]

ans[0]=0
q = deque([0])
q2 = deque()

seen = set()
seen.add(0)

for _ in range(100*n):
    while q:
        q2 = deque()
        #print(ans,q,q2,seen)
        i = q.pop()
        for j in G[i]:
            if j in seen:
                continue
            q2.append(j)
            ans[j] = i+1
            seen.add(j)
    q = q2
    if len(seen) == n:
        print("Yes")
        print(*ans[1:], sep="\n")
        sys.exit()
print("No")

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と道しるべを置く
        room = root[x, 1 - y]
        depth[room - 1] = newdepth
        toward[room - 1] = index+1
        
        
    # 処理が終われば終了
    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:
def main():
    n,m = map(int,input().split())
    ab = []
    cnt = [0] * n
    road = [[] for i in range(n)]

    for _ in range(m):
        a, b = map(int,input().split())
        ab.append([a-1,b-1])
        cnt[a-1] += 1
        cnt[b-1] += 1
        road[a-1].append(b-1)
        road[b-1].append(a-1)

    dist = [10**7] * n
    dist[0] = 0
    ans = [0] * n
    cnt = 0
    while True:
        for i, aa in enumerate(road):
            for j, t in enumerate(aa):
                if dist[i] > dist[t]+1:
                    dist[i] = dist[t]+1
                    ans[i] = t + 1
                    flg = True


        cnt += 1
        if cnt == 1000:
            break
        if flg :
            flg = False
            continue
        else:
            break

    f = 'Yes'
    for i in range(n):
        if dist[i] == 10**7:
            f = 'No'
            break
        else:
            continue
    print(f)
    for i in range(1,n):
        print(ans[i])


if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,M = map(int, input().split())
flg = 0
d = [10000000]*N
ans = [0]*N
for i in range(M):
  a,b = map(int, input().split())
  if a==1:
    d[b-1] = 1
    if ans[b-1]<0:
      d[-ans[b-1]] = d[b-1]+1
      ans[-ans[b-1]] = b-1
    ans[b-1] = 0
  elif b==1:
    d[a-1] = 1
    if ans[a-1]<0:
      d[-ans[a-1]] = d[a-1]+1
      ans[-ans[a-1]] = a-1
    ans[a-1] = 0
  else:
    if d[a-1]<1000000:
      if d[a-1]+1 < d[b-1]:
        d[b-1] = d[a-1]+1
        if ans[b-1]<0:
          d[-ans[b-1]] = d[b-1]+1
          ans[-ans[b-1]] = b-1
        ans[b-1] = a-1
    elif d[b-1] > 1000000:
      ans[b-1] = -(a-1)
    if d[b-1]<1000000:
      if d[b-1]+1 < d[a-1]:
        d[a-1] = d[b-1]+1
        if ans[a-1]<0:
          d[-ans[a-1]] = d[a-1]+1
          ans[-ans[a-1]] = a-1
        ans[a-1] = b-1
    elif d[a-1] > 1000000:
      ans[a-1] = -(b-1)

for i in range(1,N):
  if ans[i]<0:
    flg = 1
if flg==1:
  print('No')
else:
  print('Yes')
  for i in range(1,N):
    print(ans[i]+1)

Submission status: Wrong Answer

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

roads = []

for i in range(m):
    a = input().split()
    roads.append([int(a[0]), int(a[1])])

visited = [1]
shortest = [[1]]
while len(visited) < n:
    for i in range(len(shortest)):
        for j in range(len(shortest[i])):
            for k in range(len(roads)):
                if shortest[i][j] in roads[k]:
                    t = roads[k].index(shortest[i][j])
                    if roads[k][(t+1) % 2] not in visited:
                        if len(shortest) < i+2:
                            shortest.append([roads[k][(t+1) % 2]])
                        else:
                            shortest[i+1].append(roads[k][(t+1) % 2])
                        visited.append(roads[k][(t+1) % 2])
flag = False

output = [0]*(n-1)
for i in range(1, len(shortest)):
    for j in range(len(shortest[i])):
        for k in range(len(shortest[i-1])):
            if [shortest[i][j], shortest[i-1][k]] in roads:
                output[shortest[i][j]-2] = shortest[i-1][k]
            elif [shortest[i-1][k], shortest[i][j]] in roads:
                output[shortest[i][j]-2] = shortest[i-1][k]
            else:
                flag = True
                print('No')
                break
        else:
            continue
        break
    else:
        continue
    break

if flag == False:
    print('Yes')
    for i in range(len(output)):
        print(output[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=list(map(int,input().split()))

edge = np.array([input().split() for _ in range(M)], dtype = np.int64).T

graph = csr_matrix(([1]*M, (edge - 1)), (N, N))


distance_mat, processors = dijkstra(graph, directed = False, indices = [0, 1], return_predecessors = True)


if 0 in processors[0][1:]:
    print("No")
else:
    print("Yes")
    for i in range(1,len(processors[0])):
        print(processors[0][i]+1)

Submission status: Wrong Answer

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

TFl=[0 for _ in range(N)]
ml=[0 for _ in range(N)]

for i in range(N):
  l.append([])

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

for i  in range(len(l)):
  for j in range(len(l[i])):
    TFl[l[i][j]]=1
    ml[l[i][j]]=i
  if all([k==1 for k in TFl]):
    break

if all([i==1 for i in TFl]):
  print('Yes')
  for i in range(1, N):
    print(ml[i]+1)


else:
  print('No')

Submission status: Wrong Answer

Solution code:
N,M = map(int, input().split())
A = [0] * M
B = [0] * M
OK = [0] * N
for i in range(M):
    A[i], B[i] = map(int, input().split())
    if A[i] > B[i]:
      A[i],B[i] = B[i],A[i]
CT = 0
OK[0] = 1
M2 = M
while(CT!= M):
  for k in range(N):
    if OK[k] != 0:
       for i in range(M):
          if A[i] == k+1:
            OK[B[i]-1] = k+1
            CT+= 1
        
if CT == M:
  print('Yes')
  for i in range(1,N):
    print(OK[i])
else:
  print('No')

Submission status: Wrong Answer

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

#print(room_list)

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

    #print(room_list)

#回数管理
room_move_count_list = [999999] * N
room_move_count_list[0] = 0
#移動先管理
rome_move_to_list = [999999] * N
rome_move_to_list[0] = 0

flag = True
while flag:
    flag = False
    for i, room in enumerate(room_list):
        for miti in room: 
            #print(miti)
            if room_move_count_list[i] == 999999:
                flag = True
            else:
                if room_move_count_list[miti - 1] > room_move_count_list[i] + 1:
                    #print(room_move_count_list[miti - 1])
                    room_move_count_list[miti - 1] = room_move_count_list[i] + 1
                    rome_move_to_list[miti - 1] = i + 1
                
            
if max(room_move_count_list) == 999999:
    print('No')

else:
    print('Yes')
    for room in rome_move_to_list[1:]:
        print(room)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)

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

ans = [0] * (N-1)
kyori = [10 ** 6] * N
kyori[0] = 0
detekita = [0]
next_man = [[] for i in range(N)]
#dfs
def dfs(v, p, length):
    kyori[v] = length + 1
    if v != 0:
        ans[v-1] = p + 1
    for x in miti[v]:
        if x in detekita:
            continue
        detekita.append(x)
        next_man[v].append(x)
    for t in next_man[v]:
        dfs(t, v, length + 1)

dfs(0, 0, 0)
print('Yes')
for i in range(N - 1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [float("inf") for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
    L[k].sort()
L.sort(key=lambda x:x[0])
for k in range(M):
    if L[k][0] <= room[L[k][1]-1]:
        room[L[k][1]-1] = L[k][0]
    else:
        if  room[L[k][1]-1] < room[L[k][0]-1]:
            room[L[k][0]-1] = L[k][1]
    if L[k][1] <= room[L[k][0]-1]:
        room[L[k][0]-1] = L[k][1]
    else:
        if room[L[k][1]-1] > room[L[k][0]-1]:
            room[L[k][1]-1] = L[k][0]

if N >2:
    for k in range(2, N+1):
        count = 0
        l = k
        while l != 1:
            l = room[l-1]
            count+=1

            if l ==1:
                break
            if count == N-1:
                print("No")
                
                break
        else:
            continue
        break
    if count < N :
        print("Yes")
        for k in range(1, N):
            print(room[k]) 
if N ==2:
    print("Yes")
    print(1)






"""
    if room[B-1] > A:
        room[B-1] = A
    else:
        room[B-1] = min(room[B-1], room[A-1])

    if room[A-1] > B:
        room[A-1] = B
    else:
        room[A-1] = min(room[B-1], room[A-1])
    print(room)
for k in range(1, N-1):
    if room[k] > room[k+1]:
        print("No")
        break
else:
    print("Yes")
    for k in range(1, N):
        print(room[k])
"""

Submission status: Wrong Answer

Solution code:
import sys
max = 2*(10**5)+1
N, M = (int(x) for x in input().split())
root = [0]*(N-1)
distance = [max]*(N-1)
for i in range(M):
    A, B = (int(x) for x in input().split())
    if A == 1:
        root[B-2] = 1
        distance[B-2] = 1
    elif B == 1:
        root[A-2] = 1
        distance[A-2] = 1
    else:
        # Aを更新
        if distance[A-2] > distance[B-2]:
            root[A-2] = B
            distance[A-2] = distance[B-2]+1
        # Bを更新
        elif distance[A-2] < distance[B-2]:
            root[B-2] = A
            distance[B-2] = distance[A-2]+1
        elif distance[A-2] == distance[B-2] == max:
            root[A-2] = B
            root[B-2] = A
for i in distance:
    if i == max:
        print('No')
        sys.exit()
print('Yes')
for i in range(N-1):
    print(root[i])

Submission status: Wrong Answer

Solution code:
n, m=map(int, input().split())
print("Yes")
for i in range(n):
  print(i)