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:
from collections import deque
n, m = map(int, input().split())
table = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, input().split())
    table[a].append(b)
    table[b].append(a)

ans = [0] * (n + 1)
ans[1] = -1
queue = deque()
for s in table[1]:
    ans[s] = 1
    # 注目してるノード番号, ひとつ前の番号
    queue.append((s, 1))
while len(queue) > 0:
    node = queue.popleft()
    for t in table[node[0]]:
        if ans[t] != 0 or t == 0:
            continue
        ans[t] = node[0]
        queue.append((t, node[0]))
if 0 in ans[2:]:
    print("No")
else:
    for a in ans[2:]:
        print("Yes")
        print(a)

Submission status: Wrong Answer

Solution code:
N,M=map(int,input().split())
word=True
ans=[0]*(N)
lis={1}
A=sorted([sorted(list(map(int,input().split()))) for _ in range(M)])
# print(A)
for a,b in A:
#     if not(a in lis or b in lis):
#         print(ans)
#         print(a,b)
#         print(lis)
#         word=False
#         break
#     else:
#         lis.add(a)
#         lis.add(b)
#         if ans[a-1]==0:ans[a-1]=b
#         if ans[b-1]==0:ans[b-1]=a

    lis.add(a)
    lis.add(b)
    if ans[a-1]==0:ans[a-1]=b
    if ans[b-1]==0:ans[b-1]=a

# print(ans)
if word and not(ans[1:].count(0)):
    print('Yes')
    for i in ans[1:]:
        print(i)
else:
    print('No')

Submission status: Wrong Answer

Solution code:



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

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

nodes = [None] * (N+1)

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

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

# print(nodes)

checked = [0] * (N+1) 

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

dfs(0, 1, nodes[1])

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(500000)

n,m=map(int,input().split())
a=[[] for _ in range(n)]
for i in range(m):
    ta,tb=map(int, input().split())
    a[ta-1].append(tb-1)
    a[tb-1].append(ta-1)

KITENAI=900000
mk=[KITENAI]*n

def setmk(now, k):
    global mk
    #if mk[now]==KITENAI:
    for i in a[now]:
        if mk[i]>k+1:
            mk[i]=k+1
            setmk(i, k+1)

setmk(0, 0)

print("Yes")
for i in range(n-1):
    print(mk[i+1])

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())
table = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, input().split())
    table[a].append(b)
    table[b].append(a)

ans = [0] * (n + 1)
ans[1] = -1
queue = deque()
for s in table[1]:
    ans[s] = 1
    # 注目してるノード番号, ひとつ前の番号
    queue.append((s, 1))
while len(queue) > 0:
    node = queue.popleft()
    for t in table[node[0]]:
        if ans[t] != 0 or t == 0:
            continue
        ans[t] = node[0]
        queue.append((t, node[0]))
if 0 in ans[2:]:
    print("No")
else:
    for a in ans[2:]:
        print(a)

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
ans_list = [0]*(n+1)

class Node:
    def __init__(self, x):
        self.val = x
        self.adj = []

for i in range(m):
    a, b = map(int, input().split())
    Node(a).adj.append(b)
    Node(b).adj.append(a)

q = deque()
q.append(Node(1).val)

while len(q) > 0:
    node = q.popleft()

    if node is not None:
        for i in Node(node).adj:
            if ans_list[i] == 0:
                ans_list[i] = Node(node).val

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

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
node = [[0 for _ in range(n)] for _ in range(n)]
ans=[0 for _ in range(n)]
LL = [i for i in range(n)]
L=[0]
for _ in range(m):
    a,b = map(int,input().split())
    node[a-1][b-1] = 1
    node[b-1][a-1] = 1
while L:
    for i in L:
        tmp=[]
        for j in set(LL) - set(L):
            if node[j][i] == 1 and ans[j]==0:
                ans[j] = i + 1
                node[j][i] = 0
                node[i][j] = 0
                tmp.append(j)
    L=tmp
if ans.count(0)!=1:
    print('No')
else:
    for i in range(n):
        if i==0:
            print('Yes')
        else:
            print(ans[i])

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
graph_d = {}
ans_l = []
ans_d = {}
for i in range(1,n+1):
    graph_d[i] = []

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

#print (graph_d)

for i in range(1,len(graph_d)+1):
#    print (graph_d[i])
    if 1 in graph_d[i]:
        ans_d[i] = 1
        ans_l.append(i)

#print (ans_d)
#print (ans_l)
for k,v in graph_d.items():
#    print ("kv",k,v)

    if k == 1 or k in ans_l:
#        print (k,"continue")
        continue

    for j in ans_l:
#        print (j,v)
        if j in v:
            ans_d[k] = j

if len(ans_d) == n-1:
    print ("Yes")
    for i in range(2,n+1):
        print (ans_d[i])
else:
    print ("No")

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
list = [[0 for i in range(n)] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    list[a-1][b-1] = 1
    list[b-1][a-1] = 1
ok = 1
for ll in list:
    if ll == [0]*n:
        print('No')
        ok = 0
        break
else:
    print('Yes')
if ok == 1:
    for ll in list:
        if ll == list[0]:
            continue
        for j in range(len(ll)):
            if ll[j] == 1:
                print(j+1)
                break

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
root=[[] for _ in range(n)]
for i in range(m):
	a,b=map(int,input().split())
	root[a-1].append(b-1)
	root[b-1].append(a-1)
times=[0]*n
sign=[-1]*n
sign[0]=0
color=[False]*n
que=deque([0])
while que: #qが空でないのはこう表現できる
	i=que.popleft()
	if color[i]==False:
		for edge in root[i]:
			if color[edge]==False and sign[edge]==-1: #相方が親じゃなければ(親ならすでに探索済みのはず)
				sign[edge]=i
				que.append(edge)
		color[i]=True
for i in range(n-1):
	print(sign[i+1]+1)

Submission status: Wrong Answer

Solution code:
N, M = [int(i) for i in input().split()]
l = {}
for i in range(M):
    a,b = [int(j) for j in input().split()]
    a -= 1
    b -= 1
    if a in l:
        l[a].append(b)
    else:
        l[a] = [b]
    if b in l:
        l[b].append(a)
    else:
        l[b] = [a]
ans = [10**8] * N

v = []
num = 0
cnt=1

def search(idx, num):
    global cnt
    if ans[idx] > num:
        ans[idx] = num
    for i in l[idx]:
        if ans[i] <= num + 1:
            continue 
        v.append(i)
        cnt += 1

search(0,0)

for i in range(M):
    if cnt==M:
        break
    a = v
    v = []
    num += 1
    for j in a:
        search(j, num)

ret = []
for i in range(1,N):
    for j in l[i]:
        if ans[j] == ans[i] - 1:
            ret.append(j+1)
            break

if len(ret) == N - 1:
    print("Yes")
    for i in ret:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
N,M = map(int, input().split())
path = [[] for i in range(N)]
for i in range(M):
    A,B = map(int, input().split())
    path[A-1].append(B)
    path[B-1].append(A)
    
ans = [0]*N
check = [0]*N
check[0] = 1
def func(x):
    ls = []
    for i in path[x-1]:
        if check[i-1] == 0:
            ans[i-1] = x
            check[i-1] = 1
            ls.append(i)
    return ls

fls = func(1)
while True:
    clist = []
    for i in fls:
        clist += func(i)
    if clist == []:
        break
    
print('Yes')
for i in range(1,N):
    print(ans[i])

Submission status: Wrong Answer

Solution code:

#https://juppy.hatenablog.com/entry/2018/11/01/%E8%9F%BB%E6%9C%AC_python_%E5%8D%98%E4%B8%80%E6%9C%80%E7%9F%AD%E7%B5%8C%E8%B7%AF%E6%B3%952%EF%BC%88%E3%83%80%E3%82%A4%E3%82%AF%E3%82%B9%E3%83%88%E3%83%A9%E6%B3%95%EF%BC%89_%E7%AB%B6%E6%8A%80%E3%83%97
def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d

################################
n,w = map(int,input().split()) #n:頂点数　w:辺の数

cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(w):
    x,y = map(int,input().split())
    cost[x-1][y-1] = 1
    cost[y-1][x-1] = 1
ans = dijkstra(0,n,w,cost)

if float("inf") in ans:
  print("No")
else:
  print("Yes")
  for i in range(1,len(ans)):
    print(ans[i])

Submission status: Wrong Answer

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

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

A = [x[0] for x in AB]
B = [x[1] for x in AB]


ans = [0] * (N-1)

room_set = set([1])

for _ in range(N):
    for i, x in enumerate(A):
        if x in room_set:
            #print("B[i]",i, B[i], x)
            ans[B[i] - 2] = x
            room_set.add(B[i])
            del A[i]
            del B[i]
    if(min(ans) != 0):
        break

    for i, x in enumerate(B):
        if x in room_set:
            #print("A[i]",i, A[i], x)
            ans[A[i] - 2] = x
            room_set.add(A[i])
            del A[i]
            del B[i]
    if (min(ans) != 0):
        break

if(min(ans) == 0):
    print("No")


print("{} ".format('Yes'))
for i in range(N-1):
    print("{} ".format(ans[i]))

Submission status: Wrong Answer

Solution code:
import copy

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

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

def bfs():
    q = []
    q.append(0)
    depth = 1

    while len(q):
        pos = q.pop()
        adj = adj_list[pos].copy()
        adj_len = len(adj)-1
        for i, arg in enumerate(reversed(adj)):
            i = adj_len - i
            del adj_list[pos][i]
            adj_list[arg].remove(pos)
            if min_hop[arg] == 1e6:
                min_hop[arg] = depth
                q.insert(0, arg)
        depth+=1
bfs()
if not 1e6 in min_hop:
    print("Yes")
    for i in range(1, N):
        print(min_hop[i])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
n, m = map(int,input().split())
AB = [tuple(map(int, input().split())) for _ in range(m)]

def dfs(start):
    stack = []
    visited = [False] * n
    visited[start-1] = True
    stack.append(start)
    while stack:
        target = stack.pop()
        for i in g[target]:
            if not visited[i-1]:
                ans[i-2] = target
                visited[i-1] = True
                stack.append(i)

ans = [0] * (n-1)
g = dict()
for a, b in AB:
    if a in g:
        g[a].append(b)
    if b in g:
        g[b].append(a)
    if a not in g:
        g[a] = [b]
    if b not in g:
        g[b] = [a]
start = 1
dfs(start)
if len([i for i in ans if i == 0]) == 0:
    print("Yes")
    print(*ans, sep="\n")
else:
    print("No")

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())
 
direction = [N for i in range(N)]
point = [N for i in range(N)]
for i in range(M):
  if A[i] == 1:
    direction[B[i] - 1] = 1
    point[B[i] - 1] = 1
  if B[i] == 1:
    direction[A[i] - 1] = 1
    point[A[i] - 1] = 1
step = 1
k=1
unko = [i for i in range(M)]
while k != 0:
  k = 0
 
  for i in unko:
    a = point[A[i] - 1]
    b = point[B[i] - 1]
    m = min([a, b])
    if m == step and a != b:
      if a == m:
        direction[B[i] - 1] = A[i]
        point[B[i] - 1] = m+1
        unko.remove(i)
      if b == m:
        direction[A[i] - 1] = B[i]
        point[A[i] - 1] = m+1
        unko.remove(i)
      k += 1
  step += 1
print('Yes')
for i in range(N - 1):
  print(str(direction[i + 1]))

Submission status: Wrong Answer

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

arr = []

for i in range(M):
  List = list(map(int,input().split()))
  List.sort()
  arr.append(List)
arr.sort()  

ans = []
c = [ [-1,-1]for i in range(N+1)]
for i in range(M):
  
  a = arr[i][0]
  b = arr[i][1]
  
  if a == 1:
    c[b][0] = 1
    c[b][1] = 1
  if c[a][0] != -1 and c[b][0] == -1:
    c[b][0] = c[a][0] + 1
    c[b][1] = a
  elif c[b][0] != -1 and c[a][0] == -1:
    c[a][0] = c[b][0] + 1
    c[a][1] = b
  elif c[b][0] != -1 and c[a][0] != -1:
    if c[a][0] < c[b][0]:
      c[b][0] = c[a][0] + 1
      c[b][1] = a
    elif c[b][0] < c[a][0]:
      c[a][0] = c[b][0] + 1
      c[a][1] = b
        
c[0][0] = 1
ck = 0
for i in range(N+1):
  if c[i][0] == -1:
    ck = 1
if ck == 1:
  print("No")
else:
  print("Yes")
  for i in range(2,N+1):
    print(int(c[i][1]))

Submission status: Wrong Answer

Solution code:
def solve():
  n, m = map(int, input().split())
  dokutu = [0]*m
  inf = 10**100
  turo = [[] for i in range(n)]
  for i in range(m):
    dokutu[i] = list(map(int, input().split()))
    turo[dokutu[i][0]-1].append(dokutu[i][1])
    turo[dokutu[i][1]-1].append(dokutu[i][0])
  for i in range(n):
    if len(turo[i]) == 0:
      print("No")
      exit()
  check = [inf]*n
  for i in range(n):
    for j in range(len(turo[i])):
        if check[turo[i][j]-1] > i:
            check[turo[i][j]-1] = i+1
  print("Yes")
  for i in check[1:n]:
      print(i)
  return 0
 
if __name__ == "__main__":
  solve()

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]:
                    dist[i] = dist[t]+1
                    ans[i] = t + 1
                    flg = True


        cnt += 1
        if cnt == 10000:
            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
    for i in range(1,n):
        print(ans[i])


if __name__=='__main__':
    main()

def dijkstra(s,n,w):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数
    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]+1)
    return d

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m = map(int,input().split())
route = [[False for x in range(n+1)] for x in range(n+1)]
q = deque()
q.append([1,0,-1])
ans = [[float("inf"),0] for x in range(n+1)]
for i in range(m):
    a,b = map(int,input().split())
    route[a][b] = True
    route[b][a] = True
while(len(q) > 0):
    pos,point,before = q.popleft()
    if(ans[pos][0] > point):
        ans[pos][0] = point
        ans[pos][1] = before
    for x in range(n+1):
        if(route[pos][x]):
            q.append([x,point+1,pos])
            route[pos][x] = False
            route[x][pos] = False
for i in ans[1:]:
    if(i[0] == float("inf")):
        print("No")
        break
else:
    print("Yes")
    for i in ans[2:-1]:
        print(i[1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(500000)
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-1)
  l[b-1].append(a-1)
#print(l)
def dfs(p,pearent,count):
  max=0
  #print(pearent)
  if 0 in l[p]:
    return count+1
  for i in range(len(l[p])):
    if l[p][i]==pearent:continue
    tmp=dfs(l[p][i],p,count+1)
    if max<tmp:
      max=tmp
  return max
ans=[]
for i in range(1,n):
  ans.append(dfs(i,0,0))
if 10**7 in ans:
  print('No')
else:
  print('Yes')
  for i in ans:
    print(i)
#print(dfs(1,0,0))

Submission status: Wrong Answer

Solution code:
import copy

N, M = map(int, input().split())
ans = [0]*(N+1)

path = []
check = []
for neveruse in range(M):
    l = list(map(int, input().split()))
    if 1 in l:
        temp = copy.copy(l)
        temp.remove(1)
        ans[temp[0]] = 1
        check.append(temp[0])
    else:
        path.append(l)

while len(check) > 0:
    precheck = copy.copy(check)
    check = []
    for n in precheck:
        for item in path:
            if n in item:
                tmpl = copy.copy(item)

                tmpl.remove(n)

                if ans[tmpl[0]] == 0:
                    ans[tmpl[0]] = n
                    check.append(tmpl[0])
                    path.remove(item)

ans.pop(1)

if ans.count(0) > 1:
    print('No')

else:
    ans[0] = 'Yes'

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import queue
d = defaultdict(list)
n,m = [int(i) for i in input().split()]
q=  queue.Queue()
for i in range(m):
    a,b =[int(i) for i in input().split()]
    d[a].append(b)
    d[b].append(a)
l = n-1
arr = [0]*(n+2)
#print(d)
for i in d[1]:
    if arr[i]==0:
        q.put(i)
        arr[i]=1
        l-=1
    
while(not(q.empty())):
    k = q.get()
    for i in d[k]:
        if arr[i]==0 and i!=1:
            arr[i]=k
            q.put(i)
            l-=1
    if l==0:
        break
if l==0:
    print('YES')
    for i in range(2,n+1):
        print(arr[i])
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
r={}
for _ in range(m):
  a,b=map(int,input().split())
  a,b=a-1,b-1
  #print(a,b)
  if a not in r: r[a]=[]
  r[a].append(b)
  if b not in r: r[b]=[]
  r[b].append(a)

ans = {0:0}
steps = [-1]*n
steps[0]=0

Submission status: Wrong Answer

Solution code:
n, m = list(map(int, input().split(' ')))
graph = {}

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

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

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

weight = [-1 for i in range(n)]
direction = [-1 for i in range(n)]

# init 1 connected
if not 1 in graph:
    print("No")
    exit(0)

for i in graph[1]:
    weight[i-1] = 1
    direction[i-1] = 1

flag = False

for i in range(n):
    if i == 0:
        continue

    if weight[i] == 1:
        continue

    if weight[i] == -1:
        c = graph[i+1]

        dire = -1
        m = 10000000000

        for j in c:
            if weight[j-1] != -1:
                if m > weight[j-1]:
                    m = weight[j-1]
                    dire = j

        if m != 10000000000:
            flag = True
            weight[i] = m + 1

        if dire != -1:
            direction[i] = dire

if flag:
    print("Yes")

    for i, d in enumerate(direction):
        if i == 0:
            continue

        print(d)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

def edges_to_pt(s,t,n,directed=False):
    pt = [[] for _ in range(n)]
    for i in range(len(s)):
        pt[s[i]-1].append(t[i]-1)
        if not directed:
            pt[t[i]-1].append(s[i]-1)
    return pt

N,M = LI()
A,B = LIR(M,2)

pt = edges_to_pt(A,B,N)
par = [0]*N
s = 0

visited = [False]*N
visited[s] = True
S = [s]
while S:
    v = S.pop()
    for u in pt[v]:
        if not visited[u]:
            visited[u] = True
            par[u] = v
            S.append(u)

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

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.sparse import csr_matrix, coo_matrix, lil_matrix
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(str, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
import math

N, M = map(int, input().split())  # n:頂点数　w:辺の数

d = [[float("inf")] * N for i in range(N)]
# d[u][v] : 辺uvのコスト(存在しないときはinf)

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

for i in range(N):
    d[i][i] = 0  # 自身のところに行くコストは０
mst = minimum_spanning_tree(d)
r, c = mst.nonzero()

if len(r) == N-1:
    print('Yes')
    for i in r:
        print(i+1)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
#連結なので必ず'Yes'
print('Yes')
#O(NlogN)で木を作成して親ノードを返せばよい

Submission status: Wrong Answer

Solution code:
N, M  = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]
tunagari = [0]*N
ans = [0]*N
kai = [[1]]
tunagari[0] =1
for i in range(N):
    for j in kai[i]:
        sou = []
        for k in X:
            if k[0] == j and tunagari[k[1]-1] == 0:
                sou.append(k[1])
                tunagari[k[1]-1] = j
            elif k[1] == j  and tunagari[k[0]-1] == 0:
                sou.append(k[0])
                tunagari[k[0]-1] = j
        kai.append(sou)
print(*tunagari[1:])

Submission status: Wrong Answer

Solution code:
import numpy as np
N, M = map(int, input().split())
K = [list(map(int, input().split()))]
if M > 1:
    for i in range(M - 1):
        K.append(list(map(int, input().split())))
K = np.array(K)

S = [0] * N
x = []
l = []
for i in range(K.shape[0]):
    if K[i,0] == 1:
        S[K[i,1]-1] = 1
        x.append(K[i,1])
        l.append(i)
    elif K[i,1] == 1:
        S[K[i,0]-1] = 1
        x.append(K[i,0])
        l.append(i)
K = np.delete(K, l, 0)
print(x)
print(K)

while len(x) != 0:
    y = []
    l = []
    for i in range(K.shape[0]):
        for j in range(len(x)):
            if K[i,0] == x[j]:
                S[K[i,1]-1] = x[j]
                y.append(K[i,1])
                l.append(i)
            elif K[i,1] == x[j]:
                S[K[i,0]-1] = x[j]
                y.append(K[i,0])
                l.append(i)
    x = y
    K = np.delete(K, l, 0)
    print(x)
    print(K)
flag = 0
for i in range(1, len(S)):
    if S[i] == 0:
        flag = 1
        print("No")
        break
if flag == 0:
    print("Yes")
    for i in range(1, len(S)):
        print(S[i])

Submission status: Wrong Answer

Solution code:
# N 部屋の数 M通路の数
N, M = map(int, input().split())
field = [map(int, input().split()) for route in range(M)]
print(field)

Submission status: Wrong Answer

Solution code:
# セル3(変数のリセット)
input_count = 0

def func(i, routes, marks):
    update_rooms = []
    if i not in routes:
        return marks
    for j in routes[i]:
        room_idx = j
        if room_idx in marks:
            continue
        marks[room_idx] = i
        update_rooms.append(room_idx)
    for j in update_rooms:
        marks = func(j, routes, marks)
    return marks

def get_input():
    N, M =  list(map(int, input().split()))
    routes = {}
    for i in range(M):
        a, b =  list(map(int, input().split()))
        a_idx = a - 1
        b_idx = b - 1
        if a_idx in routes:
            routes[a_idx].append(b_idx)
        else:
            routes[a_idx] = [b_idx]
        
        if b_idx in routes:
            routes[b_idx].append(a_idx)
        else:
            routes[b_idx] = [a_idx]

    return N, M, routes

def write_result(marks, N):
    flag = True
    output_str = ''
    for i in range(1, N):
        if i not in marks:
            flag = False
            break
        output_str += f'{marks[i]+1}\n'
    if flag:
        print('Yes')    
        print(output_str)
    else:
        print('No')

import numpy


marks = {0:0}

N, M, routes = get_input()
try:
    marks = func(0, routes, {0: 0})
    write_result(marks, N)
except:
    pass

Submission status: Wrong Answer

Solution code:
import sys
import itertools
import numpy as np
from collections import Counter
import math

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M = map(int, input().split(' '))
G = [[] for _ in range(N+1)]
ans = [0]*(N+1)
count = 0
for i in range(M):
    A, B = map(int, input().split(' '))
    G[A].append(B)
    G[B].append(A)

s = [1]
while count < (N-1):
    ne = []
    for i in s:
        for j in G[i]:
            if ans[j] == 0:
                ans[j] = i
                count += 1
                ne.append(j)
    s = ne
print('Yes')
for i in ans[2:]:
    print(i)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
import queue

G = [{}]

def setNode(n):
  global G
  G = [{} for i in range(n)]
def addEdge(s,t,w):
  global G
  G[s][t]=w
def solve(s,t):
  global G
  fixed = {}
  q = queue.PriorityQueue()
  q.put((0,s))
  while q.empty() == False:
    w,x = q.get()
    if x == t: return w
    if x in fixed: continue
    fixed[x] = w
    for y in G[x]:
      if (y in fixed) == False:
        q.put((w + G[x][y], y))
  return None


n,m = map(int,input().split())
setNode(n)
for i in range(m):
  s,t = map(int,input().split())
  G[s-1][t-1] = 1
  G[t-1][s-1] = 1
dst = 0
print('Yes')
for src in range(1,n):
  print(solve(src,dst))

Submission status: Wrong Answer

Solution code:
import math
from collections import defaultdict


def main():
    N, M = map(int, input().split())
    A_B = [list(map(int, input().split())) for _ in range(M)]
    inf = float('inf')

    # distances = [[0 if i == j else inf for j in range(N + 1)] for i in range(N + 1)]
    signs = [-1 for _ in range(N + 1)]
    dists = [N for _ in range(N + 1)]

    path = [(a, b) if a <= b else (b, a) for a, b in A_B]

    for a, b in sorted(path, key=lambda x: (x[0], x[1])):
        if a == 1:
            dists[b] = 1
            signs[b] = 1
        elif b == 1:
            dists[a] = 1
            signs[a] = 1
        else:
            if dists[a] - dists[b] > 1:
                dists[a] = dists[b] + 1
                signs[a] = b
            elif dists[b] - dists[a] > 1:
                dists[b] = dists[a] + 1
                signs[b] = a
            else:
                pass

    # print(dists)
    # print(signs)

    print('Yes')
    for s in signs[2:]:
        print(s)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import heapq
import sys

input = sys.stdin.readline

def Dijkstra_heap(s,edge):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

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

for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    edge[a].append((a, b))
    edge[b].append((b, a))
# 頂点0までの最短距離
dist = Dijkstra_heap(0, edge)
if 10**20 in dist:
  print("No")
  exit()
print("Yes")
for i in dist[1:]:
  print(i+1)