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 math
import heapq
def dijkstra(start, w):
    # 最短距離
    distance = [math.inf]*len(w)

    distance[start] = 0

    # 最短距離が確定した頂点
    done = []
    # 次の頂点
    heap = []
    # （スタートからの距離、頂点）のタプル
    for i, d in enumerate(distance):
        heapq.heappush(heap, (d, i))

    while heap:
        # ヒープに入っているので、頂点はスタートから最も近い頂点
        p = heapq.heappop(heap)
        i = p[1]
        if i in done:
            continue
        # print(done)
        # この時点でスタートからiまでの距離が決まる
        done.append(i)
        # iに隣接する全ての頂点に対する処理
        for j, x in enumerate(w[i]):
            # x==1なら経路がある頂点j
            if x == 1 and j not in done:
                # jへの経路で最短なのを保存
                d = min(distance[j], distance[i]+x)
                distance[j] = d
                # jへの仮の最短距離dをヒープに追加
                heapq.heappush(heap, (d, j))
    return distance


s = list(map(int,input().split()))
n=s[0]
m=s[1]
mapping=[[0]*(n+1) for i in range(n+1)]

for i in range(m):
    s = list(map(int, input().split()))
    mapping[s[0]][s[1]]=1
    mapping[s[1]][s[0]] = 1

ans=dijkstra(1,mapping)
if not math.inf in ans[1:]:
    print('Yes')
    for i in ans[2:]:
        print(i)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
N, M = [int(v) for v in input().split(" ")]

paths = []
for i in range(M):
  paths.append([int(v) - 1 for v in input().split(" ")])
  
marks = [-1 for _ in range(N)]
hops = [999999999999999999999999999 for _ in range(N)]
marked = [0]
marks[0] = 0
hops[0] = 0

hops_prev = sum(hops)
while True:
  for path_index in range(M):
    path = paths[path_index]
    if path[0] in marked and path[1] in marked:
      continue
    
    for path in [(path[0], path[1]), (path[1], path[0])]:
      hop_ = hops[path[1]]
      hop = hops[path[0]] + 1
      if hop_ > hop:
        marks[path[1]] = path[0]
        hops[path[1]] = hop
        
        if path[0] in marked:
          marked.append(path[1])
        
  if hops_prev == sum(hops):
    break
  else:
    hops_prev = sum(hops)
     

if min(hops) >= 999999999999999999999999999:
  print("No")
else:
  print("Yes")
  [print(v+1) for v in marks[1:]]

Submission status: Wrong Answer

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

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

visited = [N + 100 for _ in range(N + 1)]
step = 0
visited[1] = step
que = [1]

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

while len(que) > 0:
    step += 1

    q = que.pop()

    for t in m[q]:
        if visited[t] == N + 100:
            que.append(t)
        if step <= visited[t]:
            visited[t] = step
            os[t] = q 

for o in os[2:]:
    if o == 0:
        print('No')
        break
else:
    print('Yes')
    for _o in os[2:]:
        print(_o)

Submission status: Wrong Answer

Solution code:
N,M=map(int, input().split())
a_list=[]
for i in range(M):
    a_list.append(list(map(int,input().split())))
V_list=[]
for i in range(1,N+1) :
    i_list=[]
    for item in a_list :
        if item[0]==i :
            i_list.append(item[1])
        elif item[1]==i :
            i_list.append(item[0])
    V_list.append(i_list)

s_list=[0]*N
current_V=[1]

while (0  in s_list ) :
    a=current_V.pop()
    current_list=V_list[a-1]
    for item in current_list :
        if s_list[item-1]==0 :
            current_V.append(item)
            s_list[item-1] =a
print('Yes')
for item in s_list[1:] :
    print(item)

Submission status: Wrong Answer

Solution code:
import itertools as iter
import math as m
from collections import deque

def main():
    N, M = list(map(int, input().split()))
    R = []
    for _ in range(M):
        R.append(list(map(int, input().split())))
    
    q = deque()
    s = set()
    r = [0] * (N+1)
    q.append(1)
    while any(q):
        x = q.popleft()
        s.add(x)
        for i in R:
            if i[0] == x and i[1] not in s and i[1] not in q:
                if r[i[1]] == 0:
                    r[i[1]] = i[0]
                q.append(i[1])
            if i[1] == x and i[0] not in s and i[0] not in q:
                if r[i[0]] == 0:
                    r[i[0]] = i[1]
                q.append(i[0])
        #print(r)
    print(len(s))
    if len(s) == N:
        print("Yes")
        for i in r[2:]:
            print(i)
    else:
        print("No")
    
        

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


def input():
    return sys.stdin.readline()[:-1]


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

ans = [0]*(N-1)
next_root = [0]
zumi = {}
while True:
    # 次のルートが全部探索済みなら終わり
    for root in next_root:
        if not(root in zumi):
            break
    else:
        break

    tmp_next_root = []
    for root in next_root:
        if root in zumi:
            continue
        for v in tree[root]:
            if ans[v-1] == 0:
                ans[v-1] = root+1
                tmp_next_root.append(v)
        zumi[root] = True
    next_root = tmp_next_root

if ans.count(0) == 0:
    print('Yes')
    for a in ans:
        print(a)
else:
    print('No')

Submission status: Wrong Answer

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

import numpy as np
stack = [[] for j in range(n)]
value = np.ones(n) * 1000000
# print(stack)
for i in link:
    stack[i[0]-1].append(i[1]-1)
    stack[i[1]-1].append(i[0]-1)
# print(stack)
value[0] = 0
for i in range(n):
    for j in stack[i]:
        # print('ye',i,j)
        value[j] = min(value[j],value[i]+1)

# print(value)
print('Yes')
for i in value[1:]:
    print(int(i))

Submission status: Wrong Answer

Solution code:
import math
import heapq
def dijkstra(start, w):
    # 最短距離
    distance = [math.inf]*len(w)

    distance[start] = 0

    # 最短距離が確定した頂点
    done = []
    # 次の頂点
    heap = []
    # （スタートからの距離、頂点）のタプル
    for i, d in enumerate(distance):
        heapq.heappush(heap, (d, i))

    while heap:
        print(heap)
        # ヒープに入っているので、頂点はスタートから最も近い頂点
        p = heapq.heappop(heap)
        i = p[1]
        if i in done:
            continue
        # print(done)
        # この時点でスタートからiまでの距離が決まる
        done.append(i)
        # iに隣接する全ての頂点に対する処理
        for j, x in enumerate(w[i]):
            # x==1なら経路がある頂点j
            if x == 1 and j not in done:
                # jへの経路で最短なのを保存
                d = min(distance[j], distance[i]+x)
                distance[j] = d
                # jへの仮の最短距離dをヒープに追加
                heapq.heappush(heap, (d, j))
    return distance


s = list(map(int,input().split()))
n=s[0]
m=s[1]
mapping=[[0]*(n+1) for i in range(n+1)]

for i in range(m):
    s = list(map(int, input().split()))
    mapping[s[0]][s[1]]=1
    mapping[s[1]][s[0]] = 1

ans=dijkstra(1,mapping)
print(ans)
if not math.inf in ans[1:]:
    print('Yes')
    for i in ans[2:]:
        print(i)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

N, M = map(int, readline().split())
graph = [[0] * N for _ in range(N)]
for i in range(M):
    A, B = map(int1, readline().split())
    graph[A][B] = 1
    graph[B][A] = 1
ans = [None] * (N)

visited = [False] * N
visited[0] = True

que = [0]

while len(que) > 0:
    acc = que.pop()
    for i, pos in enumerate(graph[acc]):
        if pos == 0 or visited[i]:
            continue

        ans[i] = acc + 1
        visited[i] = True
        que.append(i)

if sum(visited) == len(visited):
    print("Yes")
    for sign in ans[1:]:
        print(sign)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
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

def main():
  N,M = map(int,input().split())

  cost = [[float("inf") for i in range(N)] for i in range(N)] 
  for i in range(M):
      x,y = map(int,input().split())
      cost[x-1][y-1] = 1
      cost[y-1][x-1] = 1
  dis = dijkstra(0,N,M,cost)[1:]
  if max(dis) > M:
    print('No')
  else:
    print('Yes')
    for i in dis:
      print(i)
main()

Submission status: Wrong Answer

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

import numpy as np
stack = [[] for j in range(n)]
value = np.ones(n) * 1000000
# print(stack)
for i in link:
    stack[i[0]-1].append(i[1]-1)
    stack[i[1]-1].append(i[0]-1)
print(stack)
value[0] = 0
for i in range(n):
    for j in stack[i]:
        # print('ye',i,j)
        value[j] = min(value[j],value[i]+1)

# print(value)
print('Yes')
for i in value[1:]:
    print(int(i))

Submission status: Wrong Answer

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

R = [-1 for i in range(n)]
Q = deque([(0, -2)])
while len(Q) > 0:
    t = Q[0][0]
    b = Q[0][1]
    print(t)
    print(b)
    Q.popleft()
    if R[t] == -1:
        R[t] = b
        for i in range(len(M[t])):
            if R[M[t][i]] == -1:
                Q.append((M[t][i], t))
            else:
                pass
    else:
        pass
#print(R)

f = 0
for i in range(n):
    if R[i] == -1:
        f = 1
        break  
    else:
        pass

if f == 1:
    print('No')
else:
    print('Yes')
    for i in range(1, n):
        print(R[i] + 1)

Submission status: Wrong Answer

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

marks = [-1]*N
marks[0] = 0
now = [0]
next_ = []
cnt = 0
flag = 1
while flag==1 and cnt<N-1:
    for n in now:
        flag = 0
        next_ = []
        for r in routes[n]:
            if marks[r] == -1:
#                 print("marks",r,n)
                marks[r] = n
                next_.append(r)
                flag = 1
                cnt += 1
    now = next_
if -1 in marks:
    print("No")
else:
    print("Yes")
    for i in range(1,N):
        print(marks[i]+1)

Submission status: Wrong Answer

Solution code:
import bisect, collections, copy, heapq, itertools, math, numpy, string
import sys
from bisect import bisect_left, bisect_right, insort
from collections import deque
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def MS(): return map(str, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())
# N = I()
# A = [LI() for _ in range(N)]


n,m = map (int,input().split())
a = [0] * m
b = [0] * m
box = [[] for i in range(n)]
s = deque()
ans = [-1] * (n-1)
for i in range(m):
    a[i],b[i] = map (int,input().split())
    box[a[i]-1].append (b[i])
    box[b[i] - 1].append (a[i])
for i in range(len(box[0])):
    s.append([1,box[0][i]])

while len (s) > 0:
    k = s.popleft()
    
    if ans[k[1] - 2] == -1:
        ans[k[1] - 2] = k[0]

        for i in range(len(box[k[1] - 1])):
            s.append([k[1], box[k[1] - 1][i]])

print('Yes')
for i in range(len(ans)):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ans = {i:0 for i in range(1,N+1)}
ans[1] = 10000000
route = {i:[] for i in range(1,N+1)}
for _ in range(M):
    a,b = map(int,input().split())
    route[a].append(b)
    route[b].append(a)
x = [1]
for _ in range(M):
    for i in x:
        tmp = []
        for j in route[i]:
            #print(j)
            if ans[j] == 0:
                ans[j] = i
                tmp.append(j)
    x = tmp
    #print(ans,x)
print('Yes')
for i in ans.keys():
    if i != 1:
        print(ans[i])

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
a=[]
for i in range(m):
  a+=[list(map(int,input().split()))]
l=a[:]
print('Yes')
b=[[n+1,0]for i in range(n)]
b[0][0]=0
while len(l)>0:
  a=l[0]
  #print(a,b)
  if b[a[0]-1][0]==b[a[1]-1][0] and b[a[0]-1][0]==n+1:
    l+=[a]
  elif b[a[0]-1][0]>b[a[1]-1][0]:
    b[a[0]-1][0]=b[a[1]-1][0]+1
    b[a[0]-1][1]=a[1]
  else:
    b[a[1]-1][0]=b[a[0]-1][0]+1
    b[a[1]-1][1]=a[0]
  del l[0]
for i in range(1,n):
  print(b[i][1])
#print(b)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

n, m = map(int, readline().split())
graph = [[0] * n for _ in range(n)]
ab = [list(map(int, readline().split())) for _ in range(m)]
for a, b in ab:
    graph[a - 1][b - 1] = 1
    graph[b - 1][a - 1] = 1
_, ans = dijkstra(csr_matrix(graph), return_predecessors=True)
if any(int(v) == -9999 for v in ans[0][1:]):
    print('NO')
else:
    print('YES')
    print('\n'.join(map(str, ans[0][1:] + 1)))

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)]

graph = [[] for i in range(N+1)]
for i,j in AB:
    graph[i].append(j)
    graph[j].append(i)
    
r = [-1 for i in range(N+1)] 
Q = deque([1])
r[1] = 0
while Q:
    x = Q.pop()
    for to in graph[x]:
        if r[to] == -1:
            r[to] = x 
            Q.append(to)

print("No")
"""
for i in r[2:]:
    print(i)
"""

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


YES = "Yes"  # type: str


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    root = []
    for i in range(N):
        root.append([])
    next = [-1] * N
    for a, b in zip(A, B):
        root[a - 1].append(b - 1)
        root[b - 1].append(a - 1)

    if -1 in root:
        print("No")
        exit()
    
    s = set()
    s.add(0)

    while len(s) != 0:
        #print(s)
        #print(next)
        n = s.pop()
        for i in root[n]:
            if next[i] == -1:
                next[i] = n
                if i != 0:
                    s.add(i)

    print("Yes")
    for i in range(1, len(next)):
        print(next[i] + 1)
    

    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


def _ia(): return map(int, sys.stdin.readline().strip().split())


def main():
    n, m = _ia()
    edge = [[] for _ in range(n)]
    for _ in range(m):
        ai, bi = map(lambda x: x-1, _ia())
        edge[ai].append(bi)
        edge[bi].append(ai)

    nxt = [0] + [None] * (n-1)
    cost = [0] + [n] * (n-1)
    for _ in range(30):
        for i in range(n):
            for j in edge[i]:
                cn = cost[j] + 1
                if cost[i] >= cn:
                    nxt[i] = j + 1
                    cost[i] = cn
    print("Yes")
    return "\n".join(map(str, nxt[1:]))


if __name__ == "__main__":
    print(main())

Submission status: Wrong Answer

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

Mark = [0 for _ in range(N+1)]
path = {k: [] for k in range(1, N+1)}
for i in range(M):
    A, B = [int(i) for i in input().split()]
    path[A].append(B)
    path[B].append(A)
next = [1]
while True:
    n = next.pop()
    for x in path[n]:
        # n -> x
        if Mark[x] == 0:
            Mark[x] = n
            next.append(x)

    if not next: break

if 0 in Mark[2:]:
    print("No")
else:
    print("Yes")
    print("\n".join([str(i) for i in Mark[2:]]))

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = list(map(int, input().split()))
ab = deque([])
for _ in range(M):
  A= list(map(int, input().split()))
  ab.append(A)

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

stack = deque([1])

while stack:
  x = stack.pop()
  temp = deque([])
  for i in range(len(ab)):
    print(ab)
    c = ab.pop()
    if x in c:
      if c[0] == x:
        if done[c[1]] == 0:
          done[c[1]]+=1
          stack.appendleft(c[1])
          ans[c[1]] = x
      else:
        if done[c[0]] == 0:
          done[c[0]] +=1
          stack.appendleft(c[0])
          ans[c[0]] = x
    else:
      temp.append(c)  
  ab = temp

print('Yes')
for i in range(2,len(ans)):
  print(ans[i])

Submission status: Wrong Answer

Solution code:
N, M = list(map(int, input().split()))
a = []
b = []
for i in range(M):
    aa, bb = list(map(int, input().split()))
    a.append(aa-1)
    b.append(bb-1)
    
table = [0] * N
ans = [0] * N

table[0] = 1


#start
q = [0]

while(q):
    
    x = q[0]
    
    i=0
    while(i<len(a)):
        if i>=len(a):
            break
        if a[i] == x:
            if table[b[i]]==0:
                table[b[i]]=1
                ans[b[i]]=a[i]+1
                q.append(b[i])
                a.pop(i)
                b.pop(i)

            else:
                a.pop(i)
                b.pop(i)
                
        if i>=len(a):
            break
        if b[i] == x:
            if table[a[i]]==0:
                table[a[i]]=1
                ans[a[i]]=b[i]+1
                q.append(a[i])  
                a.pop(i)
                b.pop(i)
            else:
                a.pop(i)
                b.pop(i)
        i += 1
    
    q.pop(0)

if sum(table)==N:
    print("Yes")
    for i in range(1,N):
        print(ans[i])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

N, M = map(int, readline().split())
AB = [map(int, readline().split()) for _ in range(M)]
ans = [0] * (N-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
a,b=map(int,input().split())
List=[list(map(int,input().split())) for i in range(b)]
l=[0]*(a+1)
line=deque([1])
while line:
  i=line.popleft()
  bye=[]
  for j in range(len(List)):
    x,y=List[j]
    if x==i:
      if l[y]==0:
        l[y]=i
        bye+=[j]
        line.append(y)
    if y==i:
      if l[x]==0:
        l[x]=i
        bye+=[j]
        line.append(x)
  for p in range(len(bye)):
    List.pop(bye[p]-p)
print("yes")
for h in range(a-1):
  print(l[h+2])

Submission status: Wrong Answer

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

ans = [-1 for _ in range(N-1)]
def bfs(root):
    if root is None:
        return 
    q = deque()
    q.append(e[root])
    q.append(root)
    while q:
        r = q.popleft()
        i = q.popleft()
        for n in r:
            if ans[n-1] == -1:
                ans[n-1] = i + 1
                q.append(e[n])
                q.append(n)
bfs(0)
is_exit = True
for i in ans:
    if i == -1:
        is_exit = False
        break
if is_exit:
    print("Yes")
    for i in ans:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
data = [[] for _ in range(n)]
for i in range(m):
    ab = list(map(int, input().split()))
    data[ab[0] - 1].append(ab[1] - 1)
    data[ab[1] - 1].append(ab[0] - 1)
d = [float("inf")] * n
que = deque([])
que.append(0)
d[0] = 0
bl = True
while que:
    p = que.popleft()
    if data[p] == []:
        print("No")
        bl = False
        exit()
    for next in data[p]:
        if d[next] == float("inf"):
            que.append(next)
            d[next] = d[p] + 1
if bl:
    for j in range(n):
        if j == 0:
            print("Yes")
        else:
            print(d[j])

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

N, M = map(int, sys.stdin.readline().strip().split())

edges = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, sys.stdin.readline().strip().split())
    edges[a-1].append(b-1)
    edges[b-1].append(a-1)

q = deque()
q.append((0, -1))

# 幅優先探索
visited = set()
ans = {} # どの部屋に戻るべきか
while q:
    pos, prev = q.popleft()
    if pos in visited:
        continue
    ans[pos] = prev
    visited.add(pos)

    for next_pos in edges[pos]:
        q.append((next_pos, pos))

for (pos, prev) in sorted(ans.items()):
    if pos == 0:
        continue
    print(prev+1)

Submission status: Wrong Answer

Solution code:
from collections import  deque

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

used = [False for _ in range(N)]
INF = int(1e20)
shirube = [INF for _ in range(N-1)]


def bfs(e):
    d = deque()
    used[e] = True
    d.append(e)
    while len(d) != 0:
        ne = d.pop()
        for elm in graph[ne]:
            if shirube[elm-1] == INF:
                shirube[elm-1] = ne
            if not used[elm]:
                used[elm] = True
                d.appendleft(elm)


bfs(0)
if all(used):
    print("Yes")
    for el in shirube:
        print(el+1)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
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)

mk=[900000]*n
mk[0]=0

for i in range(n):
    for b in a[i]:
        mk[b]=min(mk[b],mk[i]+1)

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

Submission status: Wrong Answer

Solution code:
import sys


def _ia(): return map(int, sys.stdin.readline().strip().split())


def main():
    n, m = _ia()
    edge = [[] for _ in range(n)]
    for _ in range(m):
        ai, bi = map(lambda x: x-1, _ia())
        edge[ai].append(bi)
        edge[bi].append(ai)

    nxt = [0] + [None] * (n-1)
    cost = [0] + [n] * (n-1)
    for _ in range(17):
        for i in range(n):
            for j in edge[i]:
                cn = cost[j] + 1
                if cost[i] > cn:
                    nxt[i] = j + 1
                    cost[i] = cn
    print("Yes")
    return "\n".join(map(str, nxt[1:]))


if __name__ == "__main__":
    print(main())

Submission status: Wrong Answer

Solution code:
from collections import  deque

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

used = [False for _ in range(N)]
INF = int(1e20)
shirube = [INF for _ in range(N-1)]


def bfs(e):
    d = deque()
    used[e] = True
    d.append(e)
    while len(d) != 0:
        ne = d.pop()
        for elm in graph[ne]:
            if shirube[elm-1] == INF:
                shirube[elm-1] = ne
            if not used[elm]:
                used[elm] = True
                d.appendleft(elm)


bfs(0)
if all(used):
    print("Yes")
    for el in shirube:
        print(el+1)
else:
    print("No")

print(graph)

Submission status: Wrong Answer

Solution code:
N,M=map(int,input().split())
l=[set() for i in range(N)]
for i in range(M):
  a,b=map(int,input().split())
  l[a-1].add(b-1)
  l[b-1].add(a-1)
ope=[1]*N
ope[0]=0
s={0}
ans=[-1]*N
while len(s):
  news=set()
  for j in s:
    for k in l[j]:
      if ope[k]:
        news.add(k)
        ans[k]=j
        ope[k]=0
  s=news
print('yes')
for i in range(1,N):
  print(ans[i]+1)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
ne=[[] for i in range(n+1)]
for i in range(m):
  a,b=map(int,input().split())
  ne[a].append(b)
  ne[b].append(a)
print('Yes')

ans=[0]*(n+1)
i=m-1
check0=[1]
check1=[]
while(i>0):
  i=i-1
  for j in check0:
    check1+=ne[j]
    for k in ne[j]:
      if ans[k]==0:
        ans[k]=j
  check1=list(sorted(check1))
  check0=check1.copy()
for i in ans[2:]:
  print(i)

Submission status: Wrong Answer

Solution code:
# N = int(input())

import numpy as np

N,M = list(map(int, input().split()))
paths = []
connection_dic = {}

for i in range(N):
    connection_dic[i+1] = set()

for i in range(M):
    A,B = list(map(int, input().split()))
    connection_dic[A].add(B)
    connection_dic[B].add(A)

for i in range(N):
    if len(connection_dic[i+1]) == 0:
        print("No")
        exit()

ans_list = np.zeros(N-1, dtype = np.int)

current_distance = 0

parents = set([1])
next_parents = set()

while len(parents) > 0:
    current_distance += 1
    while len(parents) > 0:
        parent = parents.pop()
        for node in connection_dic[parent]:
            if ans_list[node-2] == 0:
                ans_list[node-2] = parent
                next_parents.add(node)
    parents = next_parents
    next_parents = set()

print("Yes")
for ans in ans_list:
    print(int(ans))

Submission status: Wrong Answer

Solution code:
from collections import deque

inf = 10 ** 15
mod = 10 ** 9 + 7
n,m = map(int, input().split())
# 幅優先？
ans = [-1 for i in range(n)] # i+1番目の部屋にある道しるべ
visited = [False for i in range(n)]
visited[0] = True
dicab = {}
for i in range(m):
    a,b = map(int, input().split())
    a-=1
    b-=1
    if a in dicab.keys():
        dicab[a].append(b)
        if b in dicab.keys():
            dicab[b].append(a)
        else:
            dicab[b] = [a]
    else:
        dicab[a] = [b]
        if b in dicab.keys():
            dicab[b].append(a)
        else:
            dicab[b] = [a]

def bfs():
    q = deque([0])
    while q:
        now = q.pop()
        nlist = dicab[now]
        for nextnode in nlist:
            if visited[nextnode] == True:
                continue
            if ans[nextnode] == -1:
                ans[nextnode] = now
                q.append(nextnode)
                visited[nextnode] = True

bfs()
ans[0] = 0
flag = True
for num in ans:
    if num == -1:
        flag = False
        break
if flag:
    print('Yes')
    for i in range(1,n):
        print(ans[i]+1)
else:
    print('No')

Submission status: Wrong Answer

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

siru=[-1]*(N-1)#2~~N
que=[0]

while len(que)>0:
    
    now=que.pop(0)
    nexlist=G[now]
    for nex in nexlist:
        if siru[nex-1]==-1:
            siru[nex-1]=now
            que.append(nex)
X=siru.count(-1)
if X>=1:
    print("No")
else:
    print("Yes")
    for num in siru:
        print(num+1)

Submission status: Wrong Answer

Solution code:
from collections import deque

N,M=list(map(int,input().split()))
g=[set() for _ in range(N+1)]
visit=[0]*(N+1)
anslst=[0]*(N+1)

for _ in range(M):
    a,b=list(map(int,input().split()))
    g[a].add(b)
    g[b].add(a)

q=deque([1])
visit[1]=1

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

    for v in g[u]:
        if visit[v]==1:
            continue

        anslst[v]=u
        visit[v]=1
        q.append(v)

if sum(visit)==N:
    print('YES')
    for i in range(2,N+1):
        print(anslst[i])
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
from collections import deque

INF = 10**6

n, m = map(int, input().split())
path = sorted([sorted(list(map(int, input().split()))) for i in range(m)])

room = [INF for i in range(n+1)]
room[1] = 0
ans = [0 for i in range(n+1)]
q = deque(path)

while len(q) > 0:
    p = q.popleft()
    a, b = p[0], p[1]
    if a == 1:
        room[b] = 1
        ans[b] = 1
    elif room[a] == INF and room[b] == INF:
        q.append(p)
    elif room[a] > room[b]:
        room[a] = room[b] + 1
        ans[a] = b
    elif room[a] < room[b]:
        room[b] = room[a] + 1
        ans[b] = a

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