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


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

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

route = deque([0])
dist = [0]*N
prev = [-1]*N
dist[0] = 0

while route:
    v = route.popleft()
    for u in to[v]:
        if dist[u]: continue
        dist[u] = dist[v]+1
        prev[u] = v
        route.append(u)

print("Yes")
for pre in prev[1:]:
    print(pre+1)

Submission status: Accepted

Solution code:
from collections import deque


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

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

route = deque([0])
dist = [False]*N
prev = [-1]*N
dist[0] = 0

while route:
    v = route.popleft()
    for u in to[v]:
        if dist[u]: continue
        dist[u] = dist[v]+1
        prev[u] = v
        route.append(u)

print("Yes")
for pre in prev[1:]:
    print(pre+1)

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 = [0]*(n+1)
seen = [False]*(n+1)

que = deque()
que.append(1)

while len(que) != 0:
    k = que.popleft()
    seen[k] = True
    
    for i in graph[k]:
        if seen[i]:
            continue
        ans[i] = k
        que.append(i)
        seen[i] = True

ans = ans[2:]

for i in ans:
    if i == 0:
        print('No')
        exit()

print('Yes')

for i in ans:
    print(i)

Submission status: Accepted

Solution code:
from collections import deque

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

for i in range(N+1): #リストの要素を昇順に並び替え
    g[i].sort() 
    
#部屋１までの最短距離となる次の部屋の番号をguideにそれぞれ格納
guide = [float('inf')]*(N+1) #1-index
guide[0], guide[1] = 0, 0

seen = [-1]*(N+1)
q = deque()
q.append(1)

while q:
    q_no = q.popleft()
    for next_v in g[q_no]:
            if seen[next_v] == 1: continue
            
            seen[next_v] = 1
            guide[next_v] = q_no
            q.append(next_v)

if sum(guide) == float('inf'):
    print('No')
else:
    print('Yes')
    for i in range(2,N+1):
        print(guide[i])

Submission status: Accepted

Solution code:
import collections

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

ans = [0] * (N-1)
detekita = [0] * N
detekita[0] = 1
#bfs
queue = collections.deque()
queue.append(0)
while queue:
    current_node = queue.popleft()
    for x in miti[current_node]:
        if detekita[x] == 0:
            detekita[x] = 1
            ans[x-1] = current_node + 1
            queue.append(x)


print('Yes')
for i in range(N - 1):
    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 _ in range(m):
    a,b =map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)
queue = deque([1])
visited = [False] * (n+1)
visited[0] = True
ans = [0] * (n+1)
while queue:
    node = queue.popleft()
    for xnode in graph[node]:
        if visited[xnode]:
            continue
        ans[xnode]=node
        visited[xnode]=True
        queue.append(xnode)
print("Yes")
for a in ans[2:]:
    print(a)

Submission status: Accepted

Solution code:
from queue import Queue

N,M = map(int,input().split())
graph = {}
for i in range(M):
    A,B = map(int,input().split())
    try:
        graph[A].append(B)
    except KeyError:
        graph[A] = [B]
    try:
        graph[B].append(A)
    except KeyError:
        graph[B] = [A]

q = Queue()
q.put(1)

distance = [pow(10,9) for i in range(N+1)]
distance[1] = 0
visited = [False for x in range(N+1)]
ans = [None for i in range(N+1)]
while q.qsize() > 0:
    cur = q.get()
    if visited[cur]:
        continue
    for v in graph[cur]:
        if distance[v] > distance[cur] + 1:
            distance[v] = distance[cur] + 1
            ans[v] = cur
        if not visited[v]:
            q.put(v)
    visited[cur] = True

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

Submission status: Accepted

Solution code:
import copy
import collections

#メイン部
N,M=map(int,input().split())

V=list(range(1,N+1))
H={v:set() for v in V}
L={v:None for v in V}

for i in range(M):
    v,w=map(int,input().split())
    H[v].add(w)
    H[w].add(v)

Q=collections.deque()
Q.append(V[0])

L[1]=1
n=1

while Q:
    x=Q.popleft()
    for v in H[x]:
        if L[v]!=None:
            continue
        L[v]=x
        n+=1
        Q.append(v)

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

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
u = [[] for i in range(n)]#隣接リスト
for i in range(m):
     a,b = map(int,input().split())
     a-=1#部屋何号の0-indexedへの変換
     b-=1
     u[a].append(b)
     u[b].append(a)

from collections import deque
q = deque([0])#bfsの、「次のステップで訪問予定」をためておくキュー

dist = [-1]*n
ans = [-1]*n

count=1
while q:
    i = q.popleft()
    for j in u[i]:
        if dist[j]==-1:
            dist[j]=count
            ans[j]=i+1
            q.append(j)
    count+=1

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())
ab = [list(map(int, input().split())) for i in range(m)]

# nxt: 一手で行ける部屋のリスト
q = deque([])
path = [-1] * n
nxt = [[] for _ in range(n)]
for i in range(m):
    ab[i].sort()
    # 1とつながっている経路を見つけたらqueueに入れておく
    if ab[i][0] == 1:
        q.append([ab[i][0]-1, ab[i][1]-1])
    nxt[ab[i][0]-1].append(ab[i][1]-1)
    nxt[ab[i][1]-1].append(ab[i][0]-1)


def bfs(queue, visited):
    while len(queue) > 0:
        now = queue.popleft()  # now = [現在地, 目的地]
        dst = now[1]  # dst = 目的地
        if visited[dst] == -1:  # 目的地が未訪問の場合
            visited[dst] = now[0]+1
            for i in range(len(nxt[dst])):
                q.append([dst, nxt[dst][i]])
    return visited


ans = bfs(q, path)
print("Yes")
for i in range(1, n):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque

def bfs():
  d = deque([0])
  depth = [0]*(N)
  visited = [0]*N
  de = 1
  
  visited[0] = 1
  while len(d) > 0:
    ind = d.popleft()
    de = depth[ind] + 1
    for i in graph[ind]:
      if visited[i] == 1:
        depth[i] = min(depth[i],de)        
        continue
      d.append(i)
      depth[i] = de
      visited[i] = 1

  return depth
    

N,M = map(int,input().split())
graph = {}
depth = [0]*(N+1)
for i in range(N):
  graph[i] = []
  
for i in range(M):
  a,b = map(int,input().split())
  graph[a-1].append(b-1)
  graph[b-1].append(a-1)

depth = bfs()
print('Yes')
for i in range(1,N):
  
  de = depth[i]
  l = graph[i]
  for li in l:
    if depth[li] == de-1:
      print(li+1)
      break

Submission status: Accepted

Solution code:
#template
def inputlist(): return [int(k) for k in input().split()]
#template
N,M = inputlist()
graph = [[] for _ in range(N+1)]
for i in range(M):
    A,B = inputlist()
    graph[A].append(B)
    graph[B].append(A)
ans = [0]*(N+1)
seen = [False]*(N+1)

from collections import deque
que = deque()
que.append(1)
while len(que) != 0:
    k = que.popleft()
    seen[k] = True
    for i in graph[k]:
        if seen[i]:
            continue
        ans[i] = k
        que.append(i)
        seen[i] = True
ansa = ans[2:]
n = len(ansa)
say = "Yes"
for i in range(n):
    if ansa[i] == 0:
        print("No")
        exit()
print(say)
for i in range(n):
    print(ansa[i])

Submission status: Accepted

Solution code:
n,m = (int(x) for x in input().split())
ar = [[] for i in range(n + 1)]
bfs = []
ans = [-1] * (n+1)

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

bfs.append(1)
ans[1] = 1

while(bfs):
    now = bfs.pop(0)
    for i in ar[now]:
        if ans[i] != -1:
            continue
        ans[i] = now
        bfs.append(i)

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

Submission status: Accepted

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

que = queue.Queue()
que.put(1)
result = [-1]*(N+1)
result[1] = 0
while(True):
    if que.empty():
        break
    start = que.get()
    for i in tree[start]:
        if result[i] == -1:
            result[i] = start
            que.put(i)

if -1 in result[2:]:
    print("No")
else:
    print("Yes")
    for i in result[2:]:
        print(i)

Submission status: Accepted

Solution code:
from collections import deque
n, m = map(int, input().split())
INF = 100000000

to = [[] for _ in range(100005)]
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)
print('Yes')
q = deque([])
dist = [INF] * n
pre = [-1] * n
dist[0] = 0
q.append(0)

while len(q) > 0:
    v = q.popleft()
    for i in to[v]:
        if dist[i] != INF:
            continue
        dist[i] = dist[v] + 1
        pre[i] = v
        q.append(i)

for i in range(1, n):
    ans = pre[i]
    ans += 1
    print(ans)

Submission status: Accepted

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,m = mi()
A = [[] for _ in range(n)]

for i in range(m):
    a,b = mi()
    A[a-1].append(b-1)
    A[b-1].append(a-1)

inf = 10**9
dp = [inf]*n
dp[0] = 1

from collections import deque

q = deque()
q.append((0,0))
ans = [0]*n
ans[0] = "Yes"
while q:
    kazu,iti = q.popleft()
    kazu += 1
    for l in A[iti]:
        if dp[l] > kazu:
            dp[l] = kazu
            ans[l] = iti + 1
            q.append((kazu,l))

for i in range(n):
    if dp[i] == inf:
        print("No")
        exit()
for i in range(n):
    print(ans[i])

Submission status: Accepted

Solution code:
import numpy as np
import sys
import math

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

def bfs():
    nextV = [0]
    visit[0] = 1
    total = 1
    while True:
        G = nextV
        # 次のloop用
        nextV = []
        for m in G:
            # m : 現在地
            # n : 目的地

            # mから到達可能な点nを調べる
            for n in miti[m]:
                if visit[n] == 0 :
                    # first visit
                    visit[n] = 1
                    point[n] = m
                    # 次の探索範囲を追加
                    nextV.append(n)
                    total += 1
                else:
                    continue
        if total == N :
            break

def solve():
    bfs()
    print("Yes")
    for a in point[1::]:
        print(a+1)

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import deque

N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
q = deque()
done = [-1]*N
done[0] = 1
q.appendleft(0)
while q:
    now = q.pop()
    for to in G[now]:
        if done[to] != -1: continue
        done[to] = now+1
        q.appendleft(to)
print("Yes")
print(*done[1:], sep="\n")

Submission status: Accepted

Solution code:
from collections import deque

N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
q = deque()
done = [-1]*N
done[0] = 1
q.appendleft(0)
while q:
    now = q.pop()
    for to in G[now]:
        if done[to] != -1: continue
        done[to] = now+1
        q.appendleft(to)
print("Yes")
print(*done[1:], sep="\n")

Submission status: Accepted

Solution code:
import sys 
import collections

#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
n,m = map(int,input().split())

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

bfs = [0]*(n+1)
try:
    bfs[1] = s[1][0]
except IndexError:
    print("No")
    exit()
q = collections.deque()
q.append({1:s[1]})

while  q:
    tmp = q.popleft()
    for k,v in tmp.items():
        for room in v:
            if bfs[room] == 0:
                bfs[room] = k
                q.append({room:s[room]})

if bfs.count(0) <= 1:
    print("Yes")
    for i in bfs[2:]:
        print(i)
else:
    print("No")

Submission status: Accepted

Solution code:
from collections import deque

N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
q = deque()
done = [-1]*N
def bfs(fr, now):
    done[now] = fr
    for to in G[now]:
        if done[to] != -1: continue
        q.appendleft((now, to))
q.appendleft((0, 0))
while q:
    fr, now = q.pop()
    if done[now] == -1:
        bfs(fr, now)
print("Yes")
for fr in done[1:]:
    print(fr+1)

Submission status: Accepted

Solution code:
def bfs_graph(G, start):
    from collections import deque
    # 隣接リストを食わせる
    prev = [None] * N
    dist = [-1] * N
    que = deque([start])
    dist[start] = 0
    while que:
        v = que.popleft()
        d = dist[v]
        for w in G[v]:
            if dist[w] > -1:
                continue
            dist[w] = d + 1
            prev[w] = v
            que.append(w)
    return dist, prev
N, M = map(int, input().split())
graph = [[] for _ in range(N)]
def int_(num_str):
    return int(num_str) - 1


for _ in range(M):
    a, b = map(int_, input().split())
    graph[a].append(b)
    graph[b].append(a)
_, prev = bfs_graph(graph, 0)
print("Yes")
for i in range(1, N):
    print(prev[i]+1)

Submission status: Accepted

Solution code:
import collections

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

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

bfs = [0]*(n+1)
try:
    bfs[1] = s[1][0]
except IndexError:
    print("No")
    exit()
q = collections.deque()
q.append({1:s[1]})

while  q:
    tmp = q.popleft()#現在地点からたどり着ける部屋の辞書
    for k,v in tmp.items():
        for room in v:
            if bfs[room] == 0:
                bfs[room] = k
                q.append({room:s[room]})

if bfs.count(0) <= 1:
    print("Yes")
    for i in bfs[2:]:
        print(i)
else:
    print("No")

Submission status: Accepted

Solution code:
"""
import random
import functools
import copy
import bisect
import array
import re
import collections
import heapq
import fractions
import itertools
import string
import math
from operator import itemgetter as ig
from bisect import bisect_left, bisect_right, insort_left, insort_right
from itertools import permutations, combinations, product, accumulate, groupby
from heapq import heappush, heappop
from collections import deque, defaultdict, Counter
import sys
sys.setrecursionlimit(10 ** 7)
# import numpy as np

inf = 10 ** 20
INF = float("INF")
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]
ddn9 = ddn + [(0, 0)]
'''for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:'''
"""

from collections import deque
import math
from collections import deque, defaultdict
import sys
sys.setrecursionlimit(10 ** 7)


def wi(): return list(map(int, sys.stdin.readline().split()))
# WideIntPoint


def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]


def ws(): return sys.stdin.readline().split()


def si(): return int(sys.stdin.readline())  # SingleInt


def ss(): return input()


def hi(n): return [si() for _ in range(n)]


def hs(n): return [ss() for _ in range(n)]  # HeightString


def s_list(): return list(input())


def mi(n): return [wi() for _ in range(n)]  # MatrixInt


def mip(n): return [wip() for _ in range(n)]


def ms(n): return [ws() for _ in range(n)]


def num_grid(n): return [[int(i) for i in sys.stdin.readline().split()[
    0]] for _ in range(n)]  # NumberGrid


def grid(n): return [s_list() for _ in range(n)]


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def round_up(a, b):
    """ a/b の切り上げ """
    c = (a + b - 1) / b
    return c


def lcm(a, b):
    """a,bの最小公倍数"""
    return a * b // gcd(a, b)


def floor(a, b):
    """floor(a/b) 整数値を返す"""
    c = (a - a % b)/b
    return int(c)


def main():
    N, M = wi()
    G = defaultdict(list)
    for i in range(M):
        a, b = map(int, input().split())
        G[a].append(b)
        G[b].append(a)

    #print(G)
    q = deque()
    q.append(1)
    visit = [False]*N
    dis = [-1] * N
    dis[0] = 0
    while q:
        p = q.popleft()
        visit[p-1] = True
        for n_p in G[p]:
            if visit[n_p-1] != True:
                dis[n_p-1] = p
                visit[n_p-1] = True
                q.append(n_p)

    if all(visit) == True:
        print('Yes')
        for i in range(2, N+1):
            print(dis[i-1])
    else:
        print('No')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
AB = [list(map(int,input().split())) for i in range(M)]
 
ans = [-1] * (N+1)
graph = [[] for _ in range(N+1)]
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)
    

from collections import deque
import sys
ans = [-1] * (N+1)
todo = deque([(1,0)])
while todo:
    x,parent = todo.popleft()
    # ans[x] = parent
    for y in graph[x]:
        if y == parent:
            continue
        if ans[y] != -1:
            continue
        ans[y] = x
        todo.append((y,x))
        

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

Submission status: Accepted

Solution code:
import math
import re
import copy

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

q = [0]
dist = [None] * n
dist[0] = 0
pre = [None] * n
pre[0] = 0

while len(q) != 0:
    for x in to[q[0]]:
        if dist[x] == None:
            dist[x] = dist[q[0]] + 1
            pre[x] = q[0]
            q.append(x)
    q.pop(0)

if all(z != None for z in pre):
    print("Yes")
    for i in range(1,n):
        print(pre[i] + 1)
else:
    ("No")

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
AB = [list(map(int,input().split())) for i in range(M)]
 
ans = [-1] * (N+1)
graph = [[] for _ in range(N+1)]
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)
    

from collections import deque
import sys
ans = [-1] * (N+1)
todo = deque([(1,0)])
while todo:
    x,parent = deque.popleft(todo)
    # ans[x] = parent
    for y in graph[x]:
        if y == parent:
            continue
        if ans[y] != -1:
            continue
        ans[y] = x
        todo.append((y,x))
        

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

Submission status: Accepted

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

def main():
    N, M = map(int, input().split())
    R = [[] for i in range(N + 1)]

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

    P = [-1] * (N + 1)
    P[1] = 0
    Q = deque()
    Q.append(1)

    while Q:
        v = Q.popleft()
        for r in R[v]:
            if P[r] == -1:
                P[r] = v
                Q.append(r)
    print('Yes')
    for p in P[2:]:
        print(p)
main()

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
AB = [list(map(int,input().split())) for i in range(M)]
 
ans = [-1] * (N+1)
graph = [[] for _ in range(N+1)]
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)
    

from collections import deque
import sys
ans = [-1] * (N+1)
todo = deque([(1,0)])
while todo:
    x,parent = deque.popleft(todo)
    # ans[x] = parent
    for y in graph[x]:
        if y == parent:
            continue
        if ans[y] != -1:
            continue
        ans[y] = x
        todo.append((y,x))
        

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

Submission status: Accepted

Solution code:
from collections import deque

n, m = map(int, input().split())
rooms = [[] for i in range(n + 1)] #直接行ける部屋を記録

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

route = [-1]*(n + 1)
route[1] = 0
q = deque()
q.append(1)

while q:
    v = q.popleft()
    for i in rooms[v]:
        if route[i] == -1:
            route[i] = v
            q.append(i)

print("Yes")

for i in route[2:]:
    print(i)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
AB = [list(map(int,input().split())) for i in range(M)]
 
ans = [-1] * (N+1)
graph = [[] for _ in range(N+1)]
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)
    

from collections import deque
import sys
ans = [-1] * (N+1)
todo = deque([(1,0)])
while todo:
    x,parent = deque.popleft(todo)
    #ans[x] = parent
    for y in graph[x]:
        # if y == parent:
        #     continue
        if ans[y] != -1:
            continue
        ans[y] = x
        todo.append((y,x))
        

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

Submission status: Accepted

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

q = deque([])
path = [-1] * n
ver = [[] for _ in range(n)]
for i in range(m):
    ab[i].sort()
    if ab[i][0] == 1:
        q.append([ab[i][0]-1,ab[i][1]-1])
        #path[ab[i][1]-1] = 1
    ver[ab[i][0]-1].append(ab[i][1]-1)
    ver[ab[i][1]-1].append(ab[i][0]-1)

def bfs(q, visited_list):
    while len(q) > 0:
        now = q.popleft()
        go = now[1]
        if visited_list[go] == -1:
            visited_list[go] = now[0]+1
            for i in range(len(ver[go])):
                q.append([go,ver[go][i]])
    return visited_list
ans = bfs(q,path)
print('Yes')
for i in range(1,n):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
edges = [[]for _ in range(n)]
for _ in range(m):
    a, b = map(lambda x: int(x)-1, input().split())
    edges[a].append(b)
    edges[b].append(a)

next_v = deque([0])
prev = [-1]*n
while next_v:
    v = next_v.popleft()
    for v2 in edges[v]:
        if prev[v2] != -1:
            continue
        prev[v2] = v+1
        next_v.append(v2)
print('Yes')
for x in prev[1:]:
    print(x)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys,pprint

(N,M) = map(int,input().split())
paths = {}
for i in range(1,N+1):
    paths[i] = set()
for i in range(M):
    (a,b) = map(int,input().split())
    paths[a].add(b)
    paths[b].add(a)

result = [0]*N

searchroom = []
nextsearch = []
searchroom.append(1)
while len(searchroom) > 0:
    for n in searchroom:
        for s in paths[n]:
            if result[s-1] == 0:
                result[s-1] = n
                nextsearch.append(s)
    searchroom = nextsearch.copy()
    nextsearch.clear()

# no判定
for i in result[1:]:
    if i == 0:
        print("No")
        sys.exit()
print("Yes")    
for i in result[1:]:
    print(i)

Submission status: Accepted

Solution code:
from collections import deque, defaultdict
n, m = map(int, input().split())
group = [[] for _ in range(n)]
for _ in range(m):
  a, b = map(int, input().split())
  group[a-1].append(b)
  group[b-1].append(a)
rank = [False]*n
rank[0] = True
ans = [0]*(n-1)

queue = deque([1])
while queue != deque([]):
  now = queue.popleft()
  now_group = group[now-1]
  for m in now_group:
    if rank[m-1]:
      continue
    rank[m-1] = True
    ans[m-2] = now
    queue.append(m)
if None in ans:
  print('No')
else:
  print('Yes')
  for i in range(n-1):
    print(ans[i])

Submission status: Accepted

Solution code:
def main():
    from sys import setrecursionlimit, stdin
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor, gcd
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**9+10

    
    N,M = LMIIS()
    edge = defaultdict(list)
    for i in range(M):
        a,b = LMIIS()
        edge[a].append(b)
        edge[b].append(a)



    #根が１の木を作る
    #根から子を辿って、ルートを確定させていく
    roots = deque()
    roots.append(1)
    visited = [False]*(N+1)
    visited[1] = True
    lights = [0]*(N+1)
    while len(roots) > 0:
        root = roots.popleft()
        length = visited[root]
        for v in edge[root]:
            if not visited[v]:
                visited[v] = True
                lights[v] = root
                roots.append(v)
    print('Yes')
    for i in range(2,N+1):
        print(lights[i])





main()

Submission status: Accepted

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

dist = [0] + [-1] * (n - 1)
pre = [-1] * n
search = deque([0])
while search:
    v = search.popleft()
    for u in to[v]:
        if dist[u] != -1:
            continue
        dist[u] = dist[v] + 1
        pre[u] = v
        search.append(u)

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

Submission status: Accepted

Solution code:
from math import floor,ceil,sqrt
import fractions
import itertools
from collections import deque
import heapq
N,M=map(int,input().split())
tree=[[] for _ in range(N)]
for i in range(M):
    a,b=map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
prev=[-1]*N
d=[float("inf")]
prev[0]=0
d=deque()
d.append(0)
while len(d)>0:
    v=d.popleft()
    for i in tree[v]:
        if prev[i]==-1:
            prev[i]=v
            d.append(i)
print("Yes")
for i in range(1,N):
    print(prev[i]+1)

Submission status: Accepted

Solution code:
from collections import deque
import sys

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)

que = deque([1])
ans = [0]*(N+1)

while que:
    x = deque.popleft(que)
    for i in graph[x]:
        if ans[i] != 0:
            continue
        ans[i] = x
        que.append(i)
        
for i in range(2,N+1):
    if ans[i] == 0:
        print('No')
        sys.exit()
        
print('Yes')
for i in range(2,N+1):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque

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

# [[], [], [],,,]
links = [[] for _ in range(N + 1)]
for a, b in AB:
    links[a].append(b)
    links[b].append(a)
#print('links : ' + str(links))

# [-1, -1,,,,]
result = [-1] * (N + 1)
q = deque([1])

while q:
    i = q.popleft() # 1回目は　i = 1
    #print('links[' + str(i) + '] : ' + str(links[i]))
    for j in links[i]: # j は 部屋j のことで、1回目は部屋1の隣接部屋を示す（links[1]）
        if result[j] == -1:
            result[j] = i	# つまり、1回目は部屋5,6がi=1、つまり部屋1を示す（最短）
            q.append(j)
            #print(q)
print('Yes')
#print('result : ' + str(result))
print('\n'.join(str(i) for i in result[2:]))

Submission status: Accepted

Solution code:
from queue import Queue
N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(M):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    G[A].append(B)
    G[B].append(A)
que = Queue()
que.put(0)
visit = [0] * N
ans = [0] * N
while not que.empty():
    v = que.get()
    for next_v in G[v]:
        if visit[next_v] == 1:
            continue
        ans[next_v] = v
        visit[next_v] = 1
        que.put(next_v)
print("Yes")
print(*list(map(lambda x: x+1, ans[1:])), sep='\n')

Submission status: Accepted

Solution code:
import queue
N, M = map(int, input().split())
G = [[] for _ in range(N)]
dist = [-1] * N
pre = [-1] * N

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

q = queue.Queue()
dist[0] = 0
q.put(0)

while not q.empty(): 
    v = q.get()
    for u in G[v]:
        if dist[u] != -1:
            continue
        dist[u] = dist[v] + 1
        pre[u] = v
        q.put(u)
    
print('Yes')

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