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:
import collections

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

route = {}

for i in range(M):
    A, B = map(int, input().split())

    if not A in route:
        route[A] = [B]
    else:
        route[A].append(B)

    if not B in route:
        route[B] = [A]
    else:
        route[B].append(A)

check = {
    1: 0,
}

queue = collections.deque()
queue.append(1)
result = {}

while queue:
    value = queue.popleft()
    for i in route[value]:
        if not i in check:
            queue.append(i)
            check[i] = check[value] + 1
            result[i] = value

if len(result) == N-1:
    print('Yes')
    for i in range(2, N+1):
        print(result[i])
else:
    print('No')

Submission status: Accepted

Solution code:
from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2, cos, pi
from fractions import Fraction

n, m = map(int, stdin.readline().split())
g = [[] for _ in range(n+1)]

for _ in range(m):
    a, b = map(int, stdin.readline().split())
    g[a].append(b)
    g[b].append(a)

signposts = [0]*(n+1)

queue = dq([1])

visited = [0]*(n+1)
visited[1] = 1
while queue:
    parent = queue.popleft()
    for children in g[parent]:
        if not visited[children]:
            # print('dbg:', parent, children)
            signposts[children] = parent
            queue.append(children)
            visited[children] = 1

if 0 in signposts[2:]:
    print('No')
else:
    print('Yes')
    print(*signposts[2:], sep='\n')















# t = int(stdin.readline())
# for _ in range(t):
# n, m = map(int, stdin.readline().split())
# nums = list(map(int, stdin.readline().split()))
# n = int(input())
# if n%10 in [2, 4, 5, 7, 9]:
#     print('hon')
# elif n%10 in [0, 1, 6, 8]:
#     print('pon')
# else:
#     print('bon')

# k = int(input())
# s = input()

# ans = s[:k] + ('...' if len(s) > k else '')
# print(ans)

# hrhand, minhand, hr, minut = map(int, stdin.readline().split())

# angmin =360*minut/60
# anghr =360*(hr + minut/60)/12


# totang = abs(angmin - anghr)


# print((hrhand**2 + minhand**2 - 2*hrhand*minhand*cos(totang*pi/180))**0.5)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, deque

n, m = tuple(map(int, sys.stdin.buffer.readline().split()))
L = tuple(tuple(map(int, sys.stdin.buffer.readline().split())) for _ in range(m))

# print(n, m)
# print(L)

X = [n + 1] * (n + 1)
Y = [0] * (n + 1)
d = defaultdict(set)
for a, b in L:
    d[a].add(b)
    d[b].add(a)
# print(d)

X0 = X[0]
X[1] = 0
qu = deque([1])
while qu:
  i = qu.popleft()
  cost = X[i]
  for b in d[i]:
    if X[b] == X0:
      X[b] = cost + 1
      qu.append(b)

# print(X)
s = X[0]
try:
    X.index(X[0], 1)
except ValueError:
    print('Yes')
    # for v in X[2:]:
    #     print(v)
    for i in range(2, n + 1):
      c = X[i]
      for v in d[i]:
        # print(i, c, v, X[v], c - 1== X[v])
        if c - 1 == X[v]:
          Y[i] = v
          break
    for v in Y[2:]:
        print(v)
else:
    print('No')

Submission status: Accepted

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

q = deque()
lndmrk[1] = 0
q.append(1)
while(len(q) != 0):
	v = q.popleft()
	for i in e[v]:
		if lndmrk[i] != -1:
			continue
		lndmrk[i] = v
		q.append(i)
f = 1
for i in range(2, n+1):
	if lndmrk[i] == -1:
		f = 0
if f:
	print("Yes")
	for i in range(2, n+1):
		print(lndmrk[i])
else:
	print("No")

Submission status: Accepted

Solution code:
from collections import deque

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

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

d = deque()
d.append(1)

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

if -1 in dist:
    print('No')
else:
    print('Yes',*dist[2:],sep='\n')

Submission status: Accepted

Solution code:
from collections import deque
N, M = map(int,input().split()) 
P = [list(map(int,input().split())) for i in range(M)]
A = [ [] for _ in range(N)]
#node_info = [{'node':d,'connect':[],'depth':-1,'dir':-1} for d in range(N)]

for path in P:
    A[path[1]-1].append(path[0]-1)
    A[path[0]-1].append(path[1]-1)
#print(A)

previous = [-1 for i in range(N)]
previous[0]=0

que = deque([0])

while len(que) != 0:
    v = que.popleft()
    for v_i in A[v]:
        if previous[v_i] != -1:
            continue
        else:
            que.append(v_i)
            previous[v_i] = v
for i in range(N):
    if previous[i] == -1:
        print('No')
        exit()
print('Yes')
for i in range(1,N):
    print(previous[i]+1)

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys
room_num,root_num = map(int,input().split())
#room_dis_dic = dict(zip(range(1,room_num+1),[0]+[sys.maxsize]*(room_num-1)))
connect_dic = defaultdict(set)
connected_list = [1]
next_connect_dic = {}
for _ in range(root_num):
    a,b = map(int,input().split())
    connect_dic[a].add(b)
    connect_dic[b].add(a)
    
for room_i in connected_list:
    #print(room_i)
    next_room_set = {connect_to for connect_to in connect_dic[room_i] if connect_to not in next_connect_dic.keys()}
    connected_list.extend(list(next_room_set))
    for next_room_i in next_room_set:
        next_connect_dic[next_room_i] = room_i

if len(set(range(2,room_num+1))-next_connect_dic.keys())!=0:
    print("No")
else:
    print("Yes")
    for i in range(2,room_num+1):
        print(next_connect_dic[i])

Submission status: Accepted

Solution code:
from collections import deque

def bfs(s=0):
    que = deque([s])
    visited = [False] * N
    visited[s] = True
    while que:
        v = que.popleft()
        for u in E[v]:
            if not visited[u]:
                par[u] = v
                visited[u] = True
                que.append(u)

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)
par = [-1] * N
bfs()
cnt = len([i for i in par if i == -1])
if cnt > 1:
    print('No')
else:
    print('Yes')
    for p in par[1:]:
        print(p+1)

Submission status: Accepted

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


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

from collections import deque

def main():
	n,m=MI()

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

	for _ in range(m):
		a,b=MI()
		G[a].append(b)
		G[b].append(a)

	ans=[0]*(n+1)

	Q=deque([1])
	sumi=set()

	while Q:
		now=Q.popleft()

		for next in G[now]:
			if next in sumi:
				continue
			else:
				Q.append(next)
				ans[next]=now
				sumi.add(next)

	print("Yes")

	print(*ans[2:],sep="\n")






































if __name__ == "__main__":
	main()

Submission status: Accepted

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


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

from collections import deque

def main():
	n,m=MI()

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

	for _ in range(m):
		a,b=MI()
		G[a].append(b)
		G[b].append(a)

	ans=[0]*(n+1)

	Q=deque([1])
	sumi=set()

	while Q:
		now=Q.popleft()

		for next in G[now]:
			if next in sumi:
				continue
			else:
				Q.append(next)
				ans[next]=now
				sumi.add(next)

	print("Yes")

	print(*ans[2:],sep="\n")






































if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
import collections

def main():
    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)
    q = collections.deque()
    q.append(1)
    #道しるべ
    check=[0]*(n+1)
    check[1]=1
    ans=[0]*(n+1)
    while len(q)!=0:
        v=q.popleft()#リストの左から値を抜く
        for u in g[v]:
            if check[u] == 0:
                check[u] = 1
                ans[u] = v
                q.append(u)

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

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

main()

Submission status: Accepted

Solution code:
from collections import deque
N, M = map(int, input().split())
nodes = [set() for i in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    nodes[a-1].add(b-1)
    nodes[b-1].add(a-1)
ans = [-1 for i in range(N)]
ans[0] = 0
q = deque([])
q.append(0)

cur = 0
done = set()
done.add(0)
while q:
    node = q.popleft()
    for x in nodes[node]:
        if x in done:
            continue
        q.append(x)
        done.add(x)
        ans[x] = node + 1
if -1 in ans:
    print('No')
else:
    print('Yes')
    for x in ans[1:]:
        print(x)

Submission status: Accepted

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

ans = [0] * (N+1)

d = deque()
d.append(1)
count = 0
while count != N:
    Q = d.popleft()
    for i in Mlist[Q]:
        if ans[i] == 0:
            ans[i] = Q
            d.append(i)
            count = count+1
print('Yes')
for i in range(N-1):
    print(ans[i+2])

Submission status: Accepted

Solution code:
from collections import deque

n,m,*ab = map(int, open(0).read().split())

to = [[] for _ in range(n+1)]
for i in range(0, m*2, 2):
    a = ab[i]
    b = ab[i+1]
    to[a].append(b)
    to[b].append(a)

ans = [None]*(n+1)
q = deque([1])
while q:
    p = q.pop()
    children = to[p]
    for child in children:
        if ans[child] is None:
            ans[child] = p
            q.appendleft(child)

print("Yes")
print("\n".join(map(str, ans[2:])))

Submission status: Accepted

Solution code:
from collections import deque
n,m,*ab = map(int, open(0).read().split())

to = [[] for _ in range(n+1)]
ans = [None] * (n+1)
for i in range(0, m*2, 2):
    a = ab[i]
    b = ab[i+1]
    to[a].append(b)
    to[b].append(a)

q = deque([1])
while q:
    p = q.pop()
    children = to[p]
    for child in children:
        if ans[child] is None:
            ans[child] = p
            q.appendleft(child)

print("Yes")
print("\n".join(map(str, ans[2:])))

Submission status: Accepted

Solution code:
from collections import deque

def main():
    n, m = map(int, input().split())
    to = [[] for _ in range(n+1)]
    ans = [None]*(n+1)
    for _ in range(m):
        a, b = map(int, input().split())
        to[a].append(b)
        to[b].append(a)
    q = deque([1])
    while q:
        p = q.pop()
        children = to[p]
        for child in children:
            if ans[child] is None:
                ans[child] = p
                q.appendleft(child)
    print("Yes")
    print("\n".join(list(map(str, ans[2:]))))
    

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

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

# dist = [-1 for i in range(n)]
prenodes = [-1 for i in range(n)]

G = [[] for i in range(n)]
ab = []
for i in range(m):
    ab.append(list(map(int, input().split())))

for i in range(m):
    G[ab[i][0]-1].append(ab[i][1]-1)
    G[ab[i][1]-1].append(ab[i][0]-1)
# print(G)

# dist[0] = 0
prenodes[0] = 0
que = deque([0])

while len(que) != 0:
    v = que.popleft()

    for vi in G[v]:
        if prenodes[vi] != -1:
            continue
        que.append(vi)
        # dist[vi] = dist[v] + 1
        prenodes[vi] = v

ans = "Yes"
for i in range(n):
    if prenodes[i] == -1:
        ans = "No"
        break

if ans == "No":
    print(ans)
else:
    print(ans)
    for i in range(1, n):
        print(prenodes[i]+1)

Submission status: Accepted

Solution code:
import collections

n,m=map(int, input().split())
g=[[] for _ in range(n+1)]
for i in range(m):
	a,b=map(int,input().split())
	g[a].append(b)
	g[b].append(a)

q=collections.deque()
q.append(1)
visit=[-1]*(n+1)
visit[1] = 1
ans=[0]*(n+1)
while q:
	v=q.popleft()
	for i in g[v]:
		if visit[i] == -1:
			ans[i] = v
			visit[i] = 1
			q.append(i)
print('Yes')
for i in range(2,n+1):
	print(ans[i])

Submission status: Accepted

Solution code:
import sys
from collections import deque
n,m = map(int, sys.stdin.readline().rstrip("\n").split())
edge = [[] for i in range(n)]
for i in range(m):
    a,b = map(int, sys.stdin.readline().rstrip("\n").split())
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)
footprint = [10**9+7]*n
q = deque()
footprint[0] = 0
for i in edge[0]:
    q.append((i,0))
while q:
    nn,fn = q.popleft()
    if footprint[nn] == 10**9+7:
        footprint[nn] = fn
        for i in edge[nn]:
            if footprint[i] == 10**9+7:
                q.append((i,nn))
if 10**9+7 in footprint:
    print('No')
else:
    print('Yes')
    for i in range(1,n):
        print(footprint[i]+1)

Submission status: Accepted

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

n, m = map(int, input().split())
roots = [[] for _ in range(n)]
signs = [-1 for _ in range(n)]

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

queue = deque([0])
signs[0] = 0

while queue:
    room = queue.popleft()
    for root in roots[room]:
        if signs[root] == -1:
            signs[root] = room
            queue.append(root)

print('Yes')
for i in signs[1:]:
    print(i + 1)

Submission status: Accepted

Solution code:
import queue
I=lambda:map(int,input().split())
N,M=I()
ls=[[] for _ in range(N+1)]
for _ in[0]*M:
  A,B=I()
  ls[A]+=[B]
  ls[B]+=[A]
q = queue.Queue()
v=[-1]*(N+1)
v[0]=v[1]=0
q.put(1)
while not(q.empty()):
  top=q.get()
  for l in ls[top]:
    if v[l]<0:
      v[l]=top
      q.put(l)
if -1 in v:
  print("No")
else:
  print("Yes")
  [print(k) for k in v[2::]]

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10**9)
mod = 10**9+7

N,M = I()
A = [I() for _ in range(M)]
links = [[] for _ in range(N)]
ans = [-1]*(N)
ans[0] = 0
for a,b in A:
    links[a-1].append(b-1)
    links[b-1].append(a-1)
que = deque([0])
while que:
    i = que.pop()
    for j in links[i]:
        if ans[j] == -1:
            ans[j] = i+1
            que.appendleft(j)
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())
g = [[] for _ in range(n)]
for i in range(m):
    a,b = map(lambda x:int(x)-1,input().split())
    
    g[a].append(b)
    g[b].append(a) 
to = {}   
dist = [-1 for _ in range(n)]
dist[0] = 0
q = deque()
q.append(0)
while (len(q) > 0):
    v = q.popleft()
    for nv in g[v]:
        if (dist[nv] != -1):continue
        dist[nv] = dist[v] + 1
        q.append(nv)
        to[nv] = v
        
print('Yes')
for i in range(1,n):
    print(to[i]+1)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
ans=[0]*n
num1=[[] for _ in range(n)]
def ap(num01,num02):
    num1[num01-1].append(num02)
    num1[num02-1].append(num01)
for i in range(m):
    a,b=map(int,input().split())
    ap(a,b)
queue=[1]
def apq(num01):
    queue.append(num01)
def qp():
    return queue.pop(0)
for i in range(n):
    if len(queue)==0:
        break
    num=qp()
    for j in range(len(num1[num-1])):
        if ans[num1[num-1][j]-1]==0:
            apq(num1[num-1][j])
            ans[num1[num-1][j]-1]=num
if ans.count(0)!=0:
    print("No")
else:
    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 _ in range(n+1)]

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

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

d=deque()
d.append(1)

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

ans=ans[2:]
print("Yes")
print(*ans,sep="\n")

Submission status: Accepted

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

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

ans = [None] * N
from collections import deque
q = deque([[0,-1]])
while q:
  v,parent = q.popleft()
  if ans[v] is not None:
    continue
  ans[v] = parent
  for child in G[v]:
    if ans[child] is None:
      q.append([child, v])
print("Yes")
for i in range(1,len(ans)):
  print(ans[i] + 1)

Submission status: Accepted

Solution code:
from collections import deque

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

graph = [[] for _ in range(N + 1)]
for a, b in X:
    graph[a].append(b)
    graph[b].append(a)

prevs = [-1] * (N + 1)
prevs[1] = 0
q = deque([1])

while q:
    u = q.popleft()
    for v in graph[u]:
        if prevs[v] < 0:
            prevs[v] = u
            q.append(v)
            
print("Yes")
print(*prevs[2:], sep="\n")

Submission status: Accepted

Solution code:
from collections import deque

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

def bfs():
	que=deque([])
	que.append(0)
	while que:
		p=que.popleft()
		for i in m[p]:
			if n[i]==-1:
				que.append(i)
				n[i]=p+1

bfs()

print('Yes')
for j in range(1,N):
	print(n[j])

Submission status: Accepted

Solution code:
def main():
    from collections import deque

    N, M = map(int, input().split())
    connected_rooms = [[] for i in range(N + 1)]
    
    for i in range(M):
        a, b = map(int, input().split())
        connected_rooms[a].append(b)
        connected_rooms[b].append(a)
    
    def Breadth_First_Search(root):
        queue = deque([root]) #calculate distance from the root
        distance = [None] * (N + 1) #initialize distance
        distance[root] = 0
        
        while (queue): #do BFS and calculate distance recursively
            ver = queue.popleft()
            
            for index in connected_rooms[ver]:
                if (distance[index] == None):
                    distance[index] = distance[ver] + 1
                    queue.append(i)
        
        return (distance)
    
    dist = [None] * (N + 1)
    dist[0] = True
    
    Q = deque([1])
    while (Q):
        index = Q.popleft()
        for j in connected_rooms[index]:
            if (dist[j] == None):
                dist[j] = index
                Q.append(j)
    
    if (all(dist)):
        print('Yes')
        for i in dist[2:]:
            print(i)
    else:
        print('No')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from collections import deque
 
    n,m =map(int,input().split())
    abl=[[] for i in range(n+1)]
    for i in range(m):
        a,b = map(int,input().split())
        abl[a].append(b)
        abl[b].append(a)
 
    an=[0]*(n+1)
    an[0]=1
    tg = deque([1])
    while len(tg):
        itg = tg.popleft()
        for j in abl[itg]:
            if an[j]==0:
                an[j]=itg
                tg.append(j)

    if all(an):
        print('Yes')
        for j in an[2:]:
            print(j)
    else:
        print('No')
 
main()

Submission status: Accepted

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

que = deque()
que.append(1)
dist[0] = 0
ans = [0] * n
while(len(que) != 0):
    v = que.popleft()
    for i in rooms[v-1]:
        if dist[i-1] == -1:
            dist[i-1] = dist[v-1] + 1
            que.append(i)
            ans[i-1] = v
print("Yes")
for i in ans[1:]:
    print(i)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
root = [[] for _ in range(n)]
for i in range(m):
    aa,bb =map(int,input().split())
    aa-=1
    bb-=1
    root[aa].append(bb)
    root[bb].append(aa)

from collections import deque

q = deque([(-1,0)])
been=[0]*n
ans=[0]*n
been[0]=1
while q:
    parent,now = q.popleft()
    ans[now]=parent
    
    for to in root[now]:
        if been[to]==0:
            q.append((now,to))
            been[to]=1

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

Submission status: Accepted

Solution code:
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline

N, M, *AB = map(int, read().split())
graph = [[] for _ in range(N + 1)]
for A, B in zip(*[iter(AB)] * 2):
    graph[A].append(B)
    graph[B].append(A)

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

print('Yes')
print('\n'.join(map(str, answer[2:])))

Submission status: Accepted

Solution code:
from collections import deque

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

graph = [[] for _ in range(n+1)] # 初期化
for i in range(m):
  a,b = map(int, input().split())
  graph[a].append(b)
  graph[b].append(a)
# print(graph)


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

d = deque()
d.append(1)

while d:
    v = d.popleft()
    for i in graph[v]:
        if dist[i] is None: 
            dist[i] = v
            d.append(i)

ans = dist[2:]

if all(d == None for d in dist):
  print('No')
  exit()

print('Yes')
for a in ans:
  print(a)

Submission status: Accepted

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

que = deque([0])
guideposts = [-1] * N
guideposts[0] = None

while que:
    n = que.pop()
    for to in G[n]:
        if guideposts[to] != -1:
            continue
        guideposts[to] = n
        que.appendleft(to)

print('Yes')
print(*[guisepost + 1 for guisepost in guideposts[1:]], sep="\n")