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: Accepted

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, m = mi()
    adj = [[] for _ in range(n)]
    for _ in range(m):
        a, b = mi_0()
        adj[a].append(b)
        adj[b].append(a)
    
    visited = [None] * n
    def bfs_queue_traverse(u):
        queue = deque([])
        queue.append((u, 0))
        while queue:
            current, dist = queue.popleft()
            if visited[current] is None:
                visited[current] = dist
                for v in adj[current]:
                    if visited[v] is None:
                        queue.append((v, dist+1))
    bfs_queue_traverse(0)
    # print(visited)
    print('Yes')
    for u in range(1, n):
        min_ind, minimum_dist = None, inf
        for v in adj[u]:
            if visited[v] < minimum_dist:
                min_ind, minimum_dist = v, visited[v]
        print(min_ind + 1)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M=map(int,input().split())
    edge=[[] for _ in range(N)]
    for _ in range(M):
        a,b=map(int1,input().split())
        edge[a].append(b)
        edge[b].append(a)
    que=deque([0])
    d=[INF]*N
    d[0]=0
    ans=[0]*N
    while que:
        v=que.popleft()
        for nv in edge[v]:
            if d[nv]==INF:
                d[nv]=d[v]+1
                ans[nv]=v
                que.append(nv)
    print('Yes')
    for i in range(1,N):
        print(ans[i]+1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
n,m=map(int, input().split( ))
e=[[] for _ in range(n)]

for _ in range(m):
    ai,bi=map(int, input().split( ))
    ai-=1;bi-=1
    e[ai].append(bi);e[bi].append(ai)

d=[-1]*n
p=[i for i in range(n)]
d[0]=0

q=deque()

q.append(0)

while q:
    v=q.popleft()
    for u in e[v]:
        if d[u]<0:
           d[u]=d[v]+1
           p[u]=v
           q.append(u)
        elif d[u]>d[v]+1:
            d[u]=d[v]+1
            p[u]=v
            q.append(u)
print("Yes")
for i in range(1,n):
    print(p[i]+1)

Submission status: Accepted

Solution code:
import bisect
import copy
import heapq
import sys
import itertools
import math
import queue
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
# mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]
def init_dp1(init, N): return [init for _ in range(N)]
def init_dp2(init, N, M): return [[init for _ in range(M)] for _ in range(N)]


def bfs(N, L):
    P = [0] * N
    Q = queue.Queue()
    Q.put(0)
    close = {0}
    while not Q.empty():
        v = Q.get()

        close.add(v)
        for w in L[v]:
            if w in close:
                continue
            close.add(w)
            P[w] = v
            Q.put(w)
    return P


def main():
    N, M = read_values()
    L = {i: set() for i in range(N)} 
    
    for _ in range(M):
        i, j = read_index()
        L[i].add(j)
        L[j].add(i)

    P = bfs(N, L)

    if -1 in P[1:]:
        print("No")
        return
    
    print("Yes")
    
    for p in P[1:]:
        print(p + 1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque

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

    queue = deque([0])
    visit = [-1] * N
    visit[0] = 0# 部屋1の親はないので

    while queue:
        now = queue.popleft()
        for u in adj[now]:
            if visit[u] < 0:
                queue.append(u)
                visit[u] = now
    if -1 in visit:
        print('No')
    else:
        print('Yes')
        [print(v+1) for v in visit[1:]]

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:

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

lis = [ [] for i in range(N) ]

for i in range(M):

    A,B = map(int,input().split())
    A -= 1
    B -= 1

    lis[A].append(B)
    lis[B].append(A)

from collections import deque

p = [i for i in range(N)]
d = [float("inf")] * N
d[0] = 0
q = deque([0])

while len(q) > 0:

    now = q.popleft()

    for nex in lis[now]:

        if d[nex] > d[now] + 1:
            d[nex] = d[now]
            p[nex] = now
            q.append(nex)

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

Submission status: Accepted

Solution code:
from collections import deque


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

graph = [[] for i in range(n)]
for a, b in info:
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)


visited = [False] * n
ans = [0] * n
s = 0
visited[s] = True
q = deque([s])
while q:
    v = q.popleft()
    for nxt_v in graph[v]:
        if visited[nxt_v]:
            continue
        else:
            visited[nxt_v] = True
            ans[nxt_v] = v + 1
            q.append(nxt_v)
print("Yes")
for i in range(1, n):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque

N, M = map(int, input().split())
graph = [[] for i in range(N+1)]
for i in range(M):
  a, b = map(int, input().split())
  graph[a].append(b); graph[b].append(a)

d = deque([[1, 0]])
par = [0] * (N+1)
while d:
  node, p = d.popleft()
  children = graph[node]
  for child in children:
    if child == p or par[child] != 0:
      continue
    par[child] = node
    d.append([child, node])

print('Yes')
print(*par[2:], sep='\n')

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M = MAP()

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

q = deque()
q.append(0)
ans = [None]*N
ans[0] = 0
while q:
	n = q.popleft()
	for node in graph[n]:
		if ans[node] == None:
			q.append(node)
			ans[node] = n
print("Yes")
for i in range(1, N):
	print(ans[i]+1)

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
AB=[list(map(int,input().split())) for i in range(M)]
c=[[] for i in range(N)]
for i,j in AB:
    c[i-1].append(j-1)
    c[j-1].append(i-1)
from collections import deque
def bfs(c,N,s):
    v=[0]*N
    v[s]=1
    pre=[-1]*N
    q=deque([s])
    while q:
        i=q.popleft()
        for j in c[i]:
            if v[j]==0:
                v[j]=1
                pre[j]=i
                q.append(j)
    return pre
p=bfs(c,N,0)
print('Yes',*[x+1 for x in p[1:]],sep='\n')

Submission status: Accepted

Solution code:
def main():
    N, M = map(int, input().split())
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        E[a - 1].append(b - 1)
        E[b - 1].append(a - 1)
    C = [-1] * N
    C[0] = 0
    cur = set([0])
    while cur:
        nxt = set()
        for c in cur:
            for e in E[c]:
                if C[e] != -1:
                    continue
                C[e] = c
                nxt.add(e)
        cur = nxt
    print('Yes')
    print('\n'.join(str(i + 1) for i in C[1:]))
main()

Submission status: Accepted

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

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


q = [0]
par = [-1]*N
par[0] = 0
while q:
    qq = []
    for p in q:
        for np in graph[p]:
            if par[np] == -1:
                par[np] = p+1
                qq.append(np)
    q = qq

print("Yes")
print(*par[1:], sep="\n")

Submission status: Accepted

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

import sys
sys.setrecursionlimit(300000)

YES = "Yes"  # type: str

def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    conns = [[] for _ in range(N)]
    for i in range(M):
        conns[A[i] - 1].append(B[i] - 1)
        conns[B[i] - 1].append(A[i] - 1)

    q = [0]
    ret = [-1] * N
    visited = [False] * N
    visited[0] = True
    while True:
        nex = []
        for i in q:
            for con in conns[i]:
                if not visited[con]:
                    nex.append(con)
                    ret[con] = i
                    visited[con] = True
        if len(nex) == 0:
            break
        q = nex
    for r in ret[1:]:
        if r < 0:
            print('No')
            return
    print('Yes')
    for r in ret[1:]:
        print(r + 1)
    return

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: Accepted

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

E = [[] for _ in [0]*N]
for a,b in AB:
    a -= 1
    b -= 1
    E[a].append(b)
    E[b].append(a)

def dist_bfs(N,E,start):
    d = [-1]*N
    d[start] = 0
    q = [start]
    while q:
        qq = []
        for i in q:
            di = d[i]
            for j in E[i]:
                if d[j]!=-1:continue
                d[j] = di+1
                q.append(j)
        q = qq
    return d

d = dist_bfs(N,E,0)

ans = [None]*N

for i in range(1,N):
    di = d[i]
    for j in E[i]:
        if d[j] == di-1:
            ans[i] = j+1
            break
print("Yes")
for out in ans[1:]:
    print(out)

Submission status: Accepted

Solution code:
n, m = [int(i) for i in input().split()]
e = [[] for _ in range(n)]
for _ in range(m):
    a, b = [int(i) - 1 for i in input().split()]
    e[a].append(b)
    e[b].append(a)
ans = [-2] * n
ans[0] = -1
q = [0]
for i in q:
    for j in e[i]:
        if ans[j] == -2:
            q.append(j)
            ans[j] = i
if - 2 in ans:
    print("No")
else:
    print("Yes")
    for i in ans[1:]:
        print(i+1)

Submission status: Accepted

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

e_list = [[] for i in range(N)]

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

from collections import deque

vi = 0  #change
INF = float('inf')

Q = deque([vi])

checked_list = [False]*N
checked_list[vi]=True
parent_list = [-1]*N


while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.appendleft(v1)
            parent_list[v1] = v

print("Yes")

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

Submission status: Accepted

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

N,M=map(int,input().split())
E=[[] for i in range(N+1)]

for i in range(M):
    x,y=map(int,input().split())
    E[x].append(y)
    E[y].append(x)

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

from collections import deque
Q=deque()
Q.append(1)
while Q:
    x=Q.pop()
    for to in E[x]:
        if USE[to]==-1:
            USE[to]=x
            Q.appendleft(to)

if -1 in USE:
    print("No")
else:
    print("Yes")
    print(*USE[2:])

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque
N, M = map(int, input().split())

X = [[] for i in range(N*3)]
for i in range(M):
    x, y = map(int, input().split())
    X[x-1].append(y-1)
    X[y-1].append(x-1)

Q = deque([0])
ANS = [-1] * N
ANS[0] = -2
while Q:
    x = Q.popleft()
    for c in X[x]:
        if ANS[c] == -1:
            ANS[c] = x
            Q.append(c)
print("Yes")
print("\n".join(map(str, [a + 1 for a in ANS[1:]])))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
peer = [[] for _ in range(n)]
for _ in range(m):
  a,b = map(int,input().split())
  a -= 1
  b -= 1
  peer[a].append(b)
  peer[b].append(a)
now = [0]
seen = [0 for _ in range(n)]
ans = [0 for _ in range(n)]
seen[0] = 1
while now:
  last = now
  now = []
  for x in last:
    for y in peer[x]:
      if seen[y] == 0:
        seen[y] = 1
        now.append(y)
        ans[y] = x
ans = ans[1:]
print('Yes')
for x in ans:
  print(x+1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n, m = map(int,input().split())
C = [list(map(int,input().split())) for i in range(m)]

V = [0] * (n+1)
P = [-1] * (n+1)

M = [[] for i in range(n+1)]
for i in range(m):
    M[C[i][0]].append(C[i][1])
    M[C[i][1]].append(C[i][0])

# 1始まりの場合
Q = [1]
s = 0
V[1] = 1
while s < len(Q):
    i = Q[s]
    for x in M[i]:
        # print(i,x)
        if V[x] == 0:
            V[x] = 1
            P[x] = i
            Q.append(x)
    s += 1
print("Yes")
for i in range(2, len(P)):
    print(P[i])

Submission status: Accepted

Solution code:
from collections import deque
n,m,*L=map(int,open(0).read().split())
con=[[]for _ in range(n)]
for a,b in zip(*[iter(L)]*2):
	con[a-1].append(b-1)
	con[b-1].append(a-1)
q=deque([0])
par=[-1]*n
par[0]=1
while q:
	cur=q.popleft()
	for nxt in con[cur]:
		if par[nxt]==-1:
			par[nxt]=cur+1
			q.append(nxt)
if any(x==-1 for x in par):
	print("No")
	exit()
print("Yes")
print("\n".join(map(str,par[1:])))

Submission status: Accepted

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

from collections import deque
def solve():
    prev = [-1]*N
    prev[0]='Yes'
    d = deque([(0,0)])
    while len(d):
        v,cnt = d.popleft()
        for u in edge[v]:
            if prev[u]==-1:
                prev[u]=v+1
                d.append((u,cnt+1))
    if -1 in prev:
        return ['No']
    return prev
print(*solve(),sep='\n')

Submission status: Accepted

Solution code:
from collections import deque

import sys
input = sys.stdin.readline
N, M = map(int, input().split())
G = [[] for _ in [0]*N]
for _ in [0]*M:
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)

visited = [0]*N
path = [0]*N

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

while q:
    v, p = q.popleft()
    if visited[v]:
        continue

    visited[v] = 1
    path[v] = p

    for u in G[v]:
        if visited[u]:
            continue
        q.append((u, v))

print('Yes')
for p in path[1:]:
    print(p+1)

Submission status: Accepted

Solution code:
import heapq
n, m = map(int, input().split())
G = [[] for i in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    G[a - 1].append(b - 1)
    G[b - 1].append(a - 1)
inf = 10**20
D = [inf for i in range(n)]
D[0] = 0
M = [None for i in range(n)]
Q = [(0, 0)]
heapq.heapify(Q)
while Q:
    _, x = heapq.heappop(Q)
    for y in G[x]:
        if D[x] + 1 < D[y]:
            D[y] = D[x] + 1
            M[y] = x
            heapq.heappush(Q, (D[y], y))
print('Yes')
for i in range(1, n):
    print(M[i] + 1)

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def input():
    return sys.stdin.readline().strip()

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def rangeI(it, l, r):
    for i, e in enumerate(it):
        if l <= i < r:
            yield e
        elif l >= r:
            break

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

from heapq import heappush, heappop

def dijkstra(su):
    costs = [ INF ] * (n+1)

    hq = []
    hq.append((0, su))

    while hq:
        c, u = heappop(hq)
        # log(" ", c,x,y)
        if c >= costs[u]:
            continue
        costs[u] = c

        for v in edges[u]:
            heappush(hq, (c + 1, v))

    return costs



INF = 999999999999999999999999
MOD = 10**9+7

n,m = get_nums_l()
edges = [ [] for _ in range(n+1)]
for _ in range(m):
    a,b = get_nums_l()
    edges[a].append(b)
    edges[b].append(a)


costs = dijkstra(1)



ans = [0] * (n+1)
for u in range(2, n+1):
    c = costs[u]
    for v in edges[u]:
        if costs[v]+1 == c:
            ans[u] = v
            break

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

Submission status: Accepted

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短コストを格納したリスト。
                     到達不可の場合、値はfloat("inf")
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # 始点の(最短距離, 頂点番号)をヒープに追加する

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する
                e = self.G[v][i]  # vのi個目の隣接辺e
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost  # dの更新
                    heapq.heappush(que, (d[e.to], e.to))  # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush
        return d

import sys

input=sys.stdin.readline

N,M=map(int,input().split())
pro=Dijkstra(N)
edge=[[] for i in range(N)]
for i in range(M):
    a,b=map(int,input().split())
    pro.add(a-1,b-1,1)
    pro.add(b-1,a-1,1)
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)

data=pro.shortest_path(0)

ans=[]
for i in range(1,N):
    for j in edge[i]:
        if data[j]==data[i]-1:
            ans.append(j)
            break
    else:
        print("No")
        exit()

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

Submission status: Accepted

Solution code:
from collections import deque
n,m = map(int,input().split())
path = [[] for _ in range(n)]
inf = float('inf')
for _ in range(m):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    path[a].append(b)
    path[b].append(a)
que = deque([0])
parent = [-1]*n
d = [inf]*n
d[0] = 0
while que:
    p = que.popleft()
    for nxt in path[p]:
        if d[nxt] <= d[p]+1:continue
        d[nxt] = d[p] + 1
        parent[nxt] = p+1
        que.append(nxt)
print('Yes')
print('\n'.join(str(i) for i in parent[1:]))

Submission status: Accepted

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

N, M = map(int, input().split())
adj = [[] for i in range(N)]

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

from collections import deque
q = deque()
q.append(0)

parents = [-1] * N
parents[0] = 0
while q:
    nex = q.popleft()
    for v in adj[nex]:
        if parents[v] == -1:
            parents[v] = nex
            q.append(v)

out = ['Yes']
for i in range(1, N):
    out.append(str(parents[i] + 1))
print(*out, sep='\n')

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
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)
ans=[-1]*n
ans[0]=0
print('Yes')
d=deque([0])
while d:
  now=d.pop()
  for x in l[now]:
    if ans[x]<0:
      ans[x]=now
      d.appendleft(x)
for i in range(1,n):
  print(ans[i]+1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque
import sys
try:
    from typing import List
except ImportError:
    pass

YES = "Yes"  # type: str
NO = "No"  # type: str


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    G = [[] for _ in range(N)]  # type: List[List[int]]
    for Ai, Bi in zip(A, B):
        Ai -= 1
        Bi -= 1
        G[Ai].append(Bi)
        G[Bi].append(Ai)

    ans = [-1] * N
    ans[0] = 0
    q = deque([0])
    while q:
        s = q.popleft()
        for t in G[s]:
            if ans[t] >= 0:
                continue
            ans[t] = s
            q.append(t)

    if -1 in ans:
        print(NO)
        return

    print(YES)
    for ansi in ans[1:]:
        print(ansi + 1)


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: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

N, M = map(int, input().split())
G = [[] for _ in range(N+1)]
for _ in range(M):
    A, B = map(int, input().split())
    G[A].append(B)
    G[B].append(A)
dist = [-1] * (N+1)
dist[1] = 0
queue = deque([1])
while queue:
    v = queue.popleft()
    for c in G[v]:
        if dist[c] == -1:
            dist[c] = dist[v] + 1
            queue.append(c)
print('Yes')
for v in range(2, N+1):
    for c in G[v]:
        if dist[c] < dist[v]:
            print(c)
            break

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
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 a,b in ab:
  graph[a].append(b)
  graph[b].append(a)
q = deque()
q.append(1)
ans = [0 for i in range(n+1)]
ans[1] = -1
while q:
  x = q.popleft()
  for y in graph[x]:
    if ans[y] == 0:
      ans[y] = x
      q.append(y)
print("Yes")
print(*ans[2:],sep="\n")

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
ab=[list(map(int,input().split()))for i in range(m)]
ans=[0]*n
edge=[[]for _ in range(n)]
for a,b in ab:
  edge[a-1].append(b-1)
  edge[b-1].append(a-1)
visited={0}
stack=[0]
for i in stack:
  for j in edge[i]:
    if j in visited:continue
    stack.append(j)
    visited.add(j)
    ans[j]=i+1
print("Yes")
print(*ans[1:])

Submission status: Accepted

Solution code:
import sys
from collections import deque

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

n, m = nm()
G = [list() for _ in range(n)]
for _ in range(m):
    u, v = nm()
    u -= 1; v -= 1
    G[u].append(v)
    G[v].append(u)

michi = [0]*n
dist = [n]*n
dist[0] = 0

q = deque()
q.append(0)
while q:
    v = q.popleft()
    for x in G[v]:
        if dist[x] > dist[v] + 1:
            dist[x] = dist[v] + 1
            michi[x] = v + 1
            q.append(x)
print('Yes')
prn(michi[1:])

Submission status: Accepted

Solution code:
from collections import deque
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    g[a - 1].append(b - 1)
    g[b - 1].append(a - 1)
q = deque([0])
d = [-1] * n
d[0] = 0
ans = [0] * n
print('Yes')
while q:
    p = q.popleft()
    for node in g[p]:
        if d[node] == -1:
            d[node] = d[p] + 1
            q.append(node)
        else:
            if d[node] + 1 == d[p]:
                ans[p] = node + 1
for i in range(1, n):
    print(ans[i])