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 sys
sys.setrecursionlimit(1000000)

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

room_and_connecting_room_dict = {i:set() for i in range(1,N+1)}

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

def get_child_ans(room_numbers_set): #room_number_list:前の部屋番の子ども全て
    
    next_room_numbers_set = set()
    
    for room_number in room_numbers_set:
        for child_room in room_and_connecting_room_dict[room_number]:
            if child_room not in calculated_room_numbers_set:
                ans_dict[child_room] = room_number #前の部屋番の子供は全て、前の部屋番に回答が確定する
                next_room_numbers_set.add(child_room)
                calculated_room_numbers_set.add(child_room)
 
    #終了判定
    if len(calculated_room_numbers_set) == N: #全部計算済み
        return 1
    elif len(next_room_numbers_set) == 0: #1から繋がる全てを計算したのに未計算がある
        return -1
    else: #孫がいるのでまだやる
        return get_child_ans(next_room_numbers_set)

ans_dict = dict()
ans_dict[1] = 0
calculated_room_numbers_set = set()
calculated_room_numbers_set.add(1)

is_there_ans = get_child_ans(set([1]))  

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

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)]
conn = [[] for _ in range(n)]
for a,b in ab:
    conn[a-1].append(b)
    conn[b-1].append(a)
q = deque([1])
#for x in conn[0]:
#    q.append(x)
ans = [-1 for _ in range(n)]
depth = ans[:]
depth[0] = 0
while q:
    v = q.popleft()
    d = depth[v-1]
    #print(v)
    for w in conn[v-1]:
        if depth[w-1] != -1:
            continue
        depth[w-1] = d + 1
        ans[w-1] = v
        q.append(w)
        #print(v,w,d)

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

Submission status: Accepted

Solution code:
from collections import*
(n,m),*c=[[*map(int,i.split())]for i in open(0)]
g=[[]for _ in range(n+1)]
for a,b in c:
    g[a]+=[b]
    g[b]+=[a]
q=deque([1])
r=[0]*(n+1)
while q:
    v=q.popleft()
    for i in g[v]:
        if r[i]==0:
            r[i]=v
            q.append(i)
print("Yes",*r[2:],sep="\n")

Submission status: Accepted

Solution code:

from collections import defaultdict
N,M=map(int,input().strip().split())
G=defaultdict(list)
for i in range(M):
  u,v=map(int,input().strip().split())
  G[u].append(v)
  G[v].append(u)
dist=[]
for i in range(N+1):
    dist.append([0,-1])
valid=False
Q=[1]
visited=[False]*(N+1)
visited[1]=True
while(len(Q)!=0):
  top=Q[0]
  Q.pop(0)
  for u in G[top]:
    if not visited[u]:
      Q.append(u)
      dist[u][0]=1+dist[top][0]
      dist[u][1]=top
      visited[u]=True
for pair in dist[2:]:
  if pair[0]==-1:
    valid=True
    print("No")
if not valid:
  print("Yes")
  for pair in dist[2:]:
    print(pair[1])

Submission status: Accepted

Solution code:
"""bfs"""
import sys
sys.setrecursionlimit(10**6)
n,m = map(int, input().split())

INF = 1001001001

to = [[] for _ in range(n)]
dist = [INF]*n
dist[0] = 0
ans = [-1]*n
ans[0] = [0]

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

import queue

q = queue.Queue()
searched = [0]*n
q.put(0)
#searched[0] = 1 # qに突っ込んだ時点でその頂点のsearchedを1にする

while not q.empty():
    v = q.get()
    for i in range(len(to[v])):
        u = to[v][i]
        if dist[u] != INF: continue
#        if dist[v]+1 < dist[u]:
        dist[u] = dist[v]+1
        ans[u] = v
        q.put(u)
#        searched[u] = 1 # qに突っ込んだ時点でその頂点のsearchedを1にする

if -1 not in ans:
    print('Yes')
    for i in ans[1:]: print(i+1)
else:
    print('No')

Submission status: Accepted

Solution code:
from collections import deque
n, m = map(int,input().split())
d = [[] for i in range(n)]
#print(d)
for i in range(m):
    a, b = map(int,input().split())
    a -= 1
    b -= 1
    d[a].append(b)
    d[b].append(a)
#print(d)
def bfs():
    flg = [True] * n
    ans = [0] * n
    flg[0] = False
    que = deque([0])
    #print(flg)
    while len(que) != 0:
        val = que.popleft()
        #print(d[val2])
        #print(flg)
        #print(ans)
        #print(val)

        for i in range(len(d[val])):
            if flg[d[val][i]] == True:
                que.append(d[val][i])
                flg[d[val][i]] = False
                ans[d[val][i]] = val
    return ans
ans = bfs()
#print(ans)
print('Yes')
for i in range(1,n):
    print(ans[i]+1)

Submission status: Accepted

Solution code:
import queue
N, M = map(int,input().split())
D = [[] for i in range(N)]

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

print("Yes")

dist = [0 for i in range(N)]
prev = [0 for i in range(N)]
prev[0] == 1

q = queue.Queue()
q.put(1)

while not q.empty():
  t = q.get()
  for i in D[t-1]:
    if prev[i-1] == 0:
      prev[i-1] = t
      q.put(i)

for i in prev[1:]:
  print(i)

Submission status: Accepted

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

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

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

es = [[] for _ in range(N)]
for a, b in AB:
    es[a-1].append(b-1)
    es[b-1].append(a-1)

ans = [-1] * N
ans[0] = 0

from collections import deque
que = deque([])
que.append(0)

while que:
    s = que.popleft()
    for v in es[s]:
        if ans[v] == -1:
            ans[v] = s+1
            que.append(v)

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

Submission status: Accepted

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

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

es = [[] for _ in range(N)]
for a, b in AB:
    es[a-1].append(b-1)
    es[b-1].append(a-1)

ans = [-1] * N
ans[0] = 0

from collections import deque
que = deque([])
que.append(0)

while que:
    s = que.popleft()
    for v in es[s]:
        if ans[v] == -1:
            ans[v] = s+1
            que.append(v)

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

Submission status: Accepted

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

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

es = [[] for _ in range(N)]
for a, b in AB:
    es[a-1].append(b-1)
    es[b-1].append(a-1)

ans = [-1] * N
ans[0] = 0

from collections import deque
que = deque([0])

while que:
    s = que.popleft()
    for v in es[s]:
        if ans[v] == -1:
            ans[v] = s+1
            que.append(v)

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

Submission status: Accepted

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

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

es = [[] for _ in range(N)]
for a, b in AB:
    es[a-1].append(b-1)
    es[b-1].append(a-1)

ans = [-1] * N
ans[0] = 0

import queue
que = queue.Queue()
que.put(0)

while que.qsize():
    s = que.get()
    for v in es[s]:
        if ans[v] == -1:
            ans[v] = s+1
            que.put(v)

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

Submission status: Accepted

Solution code:
import queue

N, M = map(int, input().split())
parent = [-1] * N # -1なら未訪問
adj = [[] for _ in range(N)] # 隣接リスト作成
for i in range(M):
  a, b = map(int, input().split())
  adj[a-1].append(b)
  adj[b-1].append(a)
q = queue.Queue() # 自分の部屋、親の部屋
q.put([1, 0]) # 1の親は0
while not q.empty():
  x, y = q.get()
  if parent[x-1] != -1: # もし自分の部屋が訪問済みなら
    continue
  parent[x-1] = y # 自分の部屋の親yを指定
  for i in adj[x-1]:
    if parent[i-1] == -1:
      q.put([i, x])
print('Yes')
for j in parent[1:]:
  print(j)

Submission status: Accepted

Solution code:
# ノードの開始が'0'でなく'1'であることに注意!!※※※

import sys
input = sys.stdin.readline

n, m =  map(int, input().split()) # nは頂点の数、mは辺の数
pic = [[] for _ in range(n)] # 隣接リスト_初期化

for _ in range(m): # 隣接リスト_取り込み
    a, b = map(int, input().split())
    pic[a-1].append(b-1) # ※※※
    pic[b-1].append(a-1) # ※※※

from collections import deque

def BFS(u): # 'u'を開始位置として各頂点までの距離を探索する関数
    queue = deque([u]) # dequeオブジェクトとして初期化、初期値は開始位置の'u'のみ
    dis = [None] * n # uからの距離を全ノード分初期化
    dis[u] = 0 # 自分'u'との距離は0
    ans = [-1] * n # 探索元のノードを格納する
    while queue:
        v = queue.popleft() # v:探索元のノード 
        for i in pic[v]: # pic[v]: 探索元のノードに隣接するノードのリスト
            if ans[i] == -1:
                ans[i] = v
            if dis[i] is None:
                dis[i] = dis[v] + 1
                queue.append(i)
    return ans

tmp = BFS(0) # ここは'1'ではなく'0'※※※
print('Yes')
for j in tmp[1:]:
    print(j+1) # ※※※

Submission status: Accepted

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

n, m =  map(int, input().split()) # nは頂点の数、mは辺の数
pic = [[] for _ in range(n)] # 隣接リスト_初期化
#print(n,m)

for _ in range(m): # 隣接リスト_取り込み
    a, b = map(int, input().split())
    pic[a-1].append(b-1)
    pic[b-1].append(a-1)
#print(pic)

from collections import deque

def BFS(u): # 'u'を開始位置として各頂点までの距離を探索する関数
    queue = deque([u]) # dequeオブジェクトとして初期化、初期値は開始位置の'u'のみ
    dis = [None] * n # uからの距離を全ノード分初期化
    dis[u] = 0 # 自分'u'との距離は0
    ans = [-1] * n
    #print(ans)
    while queue:
        v = queue.popleft() # v:探索元のノード 
        for i in pic[v]: # pic[v]: 探索元のノードに隣接するノードのリスト
            if ans[i] == -1:
                ans[i] = v
            if dis[i] is None:
                dis[i] = dis[v] + 1
                queue.append(i)
    return ans

# 0からの各頂点の距離
#print(BFS(0))
dis = BFS(0)
print('Yes')
for j in dis[1:]:
    print(j+1)

Submission status: Accepted

Solution code:
from collections import deque

mi = lambda:list(map(int,input().split()))
mix = lambda x:list(mi() for _ in range(x))
##########
def main(n,m,l):
    #グラフの作成
    g = creategraph(n,l)
    #独立した部屋がある場合はNG
    for i in range(1,len(g)):
        if len(g[i]) == 0:
            print("No")
            return
    #BFSで道標を作成
    navi = bfs(n,g)
    #部屋1を除く部屋の道標が更新されていなければNG
    if min(navi[2:]) == 0:
        print("No")
    else:
        print("Yes")
        for i in navi[2:]:
            print(i)

#BFS幅優先探索
def bfs(n,g):
    navi = [0]*(n+1)
    navi[1] = -1
    q = deque()
    q.append(1)
    while len(q) > 0:
        #キューから現在地を取り出す
        cp = q.popleft()
        #現在地の隣接点リストを取得
        np = g[cp]
        #隣接点が未探索ならキューに入れる＋道標更新
        for i in np:
            if navi[i] == 0:
                navi[i] = cp
                q.append(i)
    return navi

#各Nodeの隣接点を保持するリストを生成する
def creategraph(n,l):
    g = {i:[] for i in range(n+1)}
    for a,b in l:
        g[a].append(b)
        g[b].append(a)
    return g

def resolve():
    n,m = mi()
    l = mix(m)
    main(n,m,l)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

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

# dist =[-1]*n
# dist[0] = 0

q = deque([0])
prev=[-1] * n

while q:
    v = q.popleft()

    for j in r[v]:
        if prev[j]==-1:
            prev[j] = v
            q.append(j)
            # dist[j] = dist[v] + 1
            

for i in range(n):
    if i==0:
        print('Yes')
    else:
        print(prev[i]+1)

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-=1
  B-=1
  G[A].append(B)
  G[B].append(A)

searched=[0]*N
searched[0]=1
ans=[-1]*N
d=deque()
d.append(0)
while(len(d)!=0):
  tmp=d.popleft()
  for g in G[tmp]:
    if searched[g]==0:
      searched[g]=1
      d.append(g)
      ans[g]=tmp
print('Yes')
for i in ans[1:]:
  print(i+1)

Submission status: Accepted

Solution code:
from collections import deque

n, m = map(int, input().split())
ways = [tuple(map(int, input().split())) for _ in range(m)]
ans = [None] * (n+1)

hush = {}
hush[1] = True
for i in range(2, n+1):
    hush[i] = False
table = [list() for _ in range(n+1)]
for a, b in ways:
    table[a].append(b)
    table[b].append(a)

que = deque([1])
while len(que) > 0:
    room = que.popleft()
    for next in table[room]:
        if hush[next] == False:
            ans[next] = room
            que.append(next)
            hush[next] = True

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

Submission status: Accepted

Solution code:
n,m = map(int, input().split())

routes = [[] for i in range(n)]
for i in range(m):
    x,y = map(int, input().split())
    routes[x-1].append(y-1)
    routes[y-1].append(x-1)


rooms = [0 for i in range(n)] # 行ったら1,まだなら0
marks = [0 for i in range(n)] # 部屋におく道標
rooms_rate = [[0]] # ０回目、１回目、２回目、３回目…に行ける部屋
rooms[0] = 1

turn = 0
for i in rooms_rate:
    newrate = []
    for j in rooms_rate[turn]: #(turn)回目に行けた部屋から行ける部屋を調べる
        for k in routes[j]: 
            if (rooms[k] == 0): #行ったことのない部屋なら
                rooms[k] = 1
                marks[k] = j # 道標をセット
                newrate.append(k)
    rooms_rate.append(newrate)
    if (len(newrate) == 0): #新しく行けなくなったら終わり
        break
    turn = turn + 1


if(all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

Submission status: Accepted

Solution code:
import heapq
def dijkstra(G, s):
    dist = [float("inf")]*len(G)
    ret = [-1]*len(G)
    q = []
    dist[s] = 0
    heapq.heapify(q)
    heapq.heappush(q, [0, s])
    while 0 < len(q):
        pre_cost, p = heapq.heappop(q)
        if dist[p] < pre_cost:
            continue
        for v, d in G[p]:
            if dist[v] > dist[p] + d:
                dist[v] = dist[p] + d
                heapq.heappush(q, [dist[v], v])
                ret[v] = p
    return ret

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, 1])
        G[b].append([a, 1])
    ans = dijkstra(G, 1)
    f = True
    for i in range(2, n+1):
        if ans[i] == -1:
            f = False
    if f:
        print("Yes")
        for i in range(2, n+1):
            print(ans[i])
    else:
        print("No")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n, m = map(int, input().split())

#グラフをリストにする
#リストの第i番目の集合は、頂点iが繋がっている頂点の集合である
l = [[] for _ in range(n+1)]
for _ in range(m):
  a, b = map(int, input().split())
  l[a].append(b)
  l[b].append(a)
  
#解（道しるべとなる点）を保存するリストを作る
ans = [-1] * (n+1)
ans[1] = 0

#解（道しるべとなる点）を書き込んでいく
#深さdの点の集合をxに、d＋１の集合をyとする
#yの要素は、l[i]と一致する
x = [1]
y = []
while x != []:
  for i in x:
    for j in l[i]:
      if ans[j] == -1:
        ans[j] = i
        y.append(j)
  x = y
  y = []
print('Yes')
for i in range(2, n+1):
  print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque, defaultdict

N, M = map(int, input().split())
outs = defaultdict(list)

for _ in range(M):
    v1, v2 = map(int, input().split())
    #v1, v2 = v1-1,v2-1
    outs[v1].append(v2)
    outs[v2].append(v1)

# print(outs)
q = deque([1])
depth = defaultdict(int)
depth[1] = 0
visit = [False]*N #配列なので0オリジン
visit[0] = True
# print(visit)
while q:
    v1 = q.popleft()
    # print("a",v1)
    for v2 in outs[v1]: #v1のノードから出ている矢印をみる．
        # print("b",v2)
        if visit[v2-1]==False:
            visit[v2-1] = True
            depth[v2] = v1
            q.append(v2)
            # print(v2,q,depth)

b = sorted(depth.items())
# print(b)
print("Yes")
for i in range(1,N):
    print(b[i][1])

Submission status: Accepted

Solution code:
from collections import deque

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)

    #print("->", g)


def bfs(u):
    queue = deque([u])
    d = [None] * (N + 1)
    d[0] = 0
    d[u] = 0

    while queue:
        v = queue.popleft()
        for i in g[v]:
            if d[i] is None:
                #d[i] = d[v] + 1
                d[i] = v
                queue.append(i)
    
    return d

d = bfs(1)

if None in d:
    print("No")
else:
    print("Yes")
    for i in d[2:]:
        print(i)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque

V, E = map(int, input().split())
# 隣接リストはdefaultdictで管理すると楽
G = defaultdict(lambda: [])

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

INF = 10 ** 18
dist = [INF] * V
parent = [-1] * V  # 親ノード
q = deque()

dist[0] = 0
q.append(0)
while q:
    now = q.popleft()  # v: 探索起点
    for to in G[now]:  # u: 隣接リストの接続先
        if dist[to] != INF:  # uをすでに探索していたらINFではない。
            continue
        dist[to] = dist[now] + 1  # 距離の更新
        parent[to] = now
        q.append(to)

print("Yes")
for i in range(1, V):
    print(parent[i] + 1)

Submission status: Accepted

Solution code:
from collections import deque
N, M = map(int, input().split())

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

q = deque([0])
ans = [-1] * N
while(len(q) > 0):
    now = q.popleft()

    for i in node[now]:
        if ans[i] == -1:
            q.append(i)
            ans[i] = now


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)]
 
l = [[] for i in range(N + 1)]
 
for i in range(M):
    a = AB[i][0]
    b = AB[i][1]
    l[a].append(b)
    l[b].append(a)
 
point = [0] * (N + 1)
search = [0] * (N + 1)
search[1] = 1

que = []
que.append(1)
p = 0

while len(que) != N:
    now = que[p]
    for i in range(len(l[now])):
        n = l[now][i]
        if search[n] == 0:
            search[n] = 1
            que.append(n)
            point[n] = now
    p += 1
    
print('Yes')
for i in range(2,N+1):
    print(point[i])

Submission status: Accepted

Solution code:
import heapq


def dijkstra_heap(s):
    d = [float("inf")] * n
    prev = [float("inf")] * n
    d[s] = 0
    edgelist = [[d[s], s]]
    heapq.heapify(edgelist)

    while edgelist:
        dis, v = heapq.heappop(edgelist)
        if d[v] < dis:
            continue

        for e in edge[v]:
            if d[e] > dis + 1:
                d[e] = dis + 1
                heapq.heappush(edgelist, [dis + 1, e])
                prev[e] = v
    return d, prev


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

edge = [[] for i in range(n)]
for i in range(w):
    x, y = map(int, input().split())
    x -= 1
    y -= 1
    edge[x].append(y)
    edge[y].append(x)
d, prev = dijkstra_heap(0)

if float('inf') in prev[1:]:
    print('No')
else:
    print('Yes')
    for i in prev[1:]:
        print(i + 1)

Submission status: Accepted

Solution code:
import sys
from collections import deque


def main():
    n, m = map(int, sys.stdin.readline().split())

    to = [[] for _ in range(n + 1)]
    for _ in range(m):
        a, b = map(int, sys.stdin.readline().split())
        to[a].append(b)
        to[b].append(a)
    INF = float("inf")

    dist = [INF] * (n + 1)
    dist[1] = 0
    pre = [0] * (n + 1)
    que = deque([])
    que.append(1)

    while que:
        p = que.popleft()
        for i in to[p]:
            if dist[i] > dist[p] + 1:
                dist[i] = dist[p] + 1
                pre[i] = p
                que.append(i)

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque


def main():
    n, m = map(int, sys.stdin.readline().split())

    to = [[] for _ in range(n + 1)]
    for _ in range(m):
        a, b = map(int, sys.stdin.readline().split())
        to[a].append(b)
        to[b].append(a)
    INF = float("inf")

    dist = [INF] * (n + 1)
    dist[1] = 0
    pre = [0] * (n + 1)
    que = deque([])
    que.append(1)

    while que:
        p = que.popleft()
        for i in to[p]:
            if dist[i] == INF:
                dist[i] = dist[p] + 1
                pre[i] = p
                que.append(i)

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

n, m = map(int, sys.stdin.readline().split())

to = [[] for _ in range(n + 1)]
for _ in range(m):
    a, b = map(int, sys.stdin.readline().split())
    to[a].append(b)
    to[b].append(a)
INF = float("inf")

dist = [INF] * (n + 1)
dist[1] = 0
pre = [0] * (n + 1)
que = deque([])
que.append(1)

while que:
    p = que.popleft()
    for i in to[p]:
        if dist[i] > dist[p] + 1:
            dist[i] = dist[p] + 1
            pre[i] = p
            que.append(i)

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

Submission status: Accepted

Solution code:
from collections import deque
n,m=map(int,input().split())
path=[[] for _ in range(n+1)]
for i in range(m):
  a,b=map(int,input().split())
  path[b].append(a)
  path[a].append(b)
q=deque()
q.append(1)
l=[-1]*(n+1)
while q:
  v=q.popleft()
  for i in path[v]:
    if l[i]==-1:
      l[i]=v
      q.append(i)
print('Yes')
for i in l[2:]:
  print(i)

Submission status: Accepted

Solution code:
from collections import deque
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([a, b])
    g[b].append([b, a])
res = [-1 for _ in range(n+1)]
res[1] = 0
q = deque(g[1])
while q:
    q_ = q.popleft()
    if res[q_[1]] == -1:
        for gi in g[q_[1]]: q.append(gi)
        res[q_[1]] = q_[0]
print("Yes")
for i in res[2:]: print(i)

Submission status: Accepted

Solution code:
from collections import deque
INF = 10**9 + 7
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([a, b])
    g[b].append([b, a])
res = [INF for _ in range(n+1)]
res[1] = 0
q = deque(g[1])
while q:
    q_ = q.popleft()
    if res[q_[1]] == INF:
        for gi in g[q_[1]]: q.append(gi)
        res[q_[1]] = q_[0]
print("Yes")
for i in res[2:]: print(i)

Submission status: Accepted

Solution code:
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)
  l[b-1].append(a)
ans=[-1]*n
ans[0]=0
x=[1]
y=[]
count=1
while x!=[]:
  for i in x:
    for j in l[i-1]:
      if ans[j-1]==-1:
        ans[j-1]=i
        y.append(j)
        count+=1
  x=y
  y=[]
print('Yes')
for i in range(1,n):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque
INF = 10**9 + 7
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([a, b])
    g[b].append([b, a])
res = [[0, INF] for _ in range(n+1)]
res[1][1] = 0
q = deque(g[1])
while q:
    q_ = q.popleft()
    if res[q_[1]][1] == INF:
        for gi in g[q_[1]]: q.append(gi)
        res[q_[1]][0] = q_[0]
        res[q_[1]][1] = res[q_[0]][1] + 1
print("Yes")
for i in res[2:]: print(i[0])

Submission status: Accepted

Solution code:
from collections import deque
n, m = map(int, input().split())
to = [[] for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1; b -= 1
    to[a].append(b)
    to[b].append(a)
q = deque()
visited = [0 for _ in range(n)]
pre = [-1 for _ in range(n)]
q.append(0)
visited[0] = 1
while q:
    # visitした
    v = q.popleft()
    for u in to[v]:
        if visited[u] == 1: continue
        visited[u] = 1
        pre[u] = v
        q.append(u)
print("Yes")
for p in pre[1:]:
    p += 1
    print(p)

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)

q = deque()
q.append(0)
dist = [-1 for _ in range(n)]
dist[0] = 0
to = {}

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

    for nv in g[v]:
        if(dist[nv] != -1): continue
        
        dist[nv] = dist[v] + 1
        to[nv] = v
        q.append(nv)

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

Submission status: Accepted

Solution code:
from collections import deque

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

ans = [0] * (n - 1) 
seen = deque([1])
not_seen = [True] * n
not_seen[0] = False
cnt = n - 1

while cnt > 0:
    pre = seen.popleft()
    for now in path[pre]:
        if not_seen[now - 1]:
            seen.append(now)
            ans[now - 2] = pre
            not_seen[now - 1] = False
            cnt -= 1

print("Yes")
for i in ans:
    print(i)

Submission status: Accepted

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

visited = [False]*N
q = deque([0])
visited[0] = True
ans = defaultdict(int)
while len(q):
    v = q.popleft()
    for e in tree[v]:
        if visited[e]:
            continue
        visited[e] = True
        ans[e] = v
        q.append(e)
print("Yes")
for i in range(1, N):
    print(ans[i]+1)

Submission status: Accepted

Solution code:
from collections import deque

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)
D=[float('inf') for i in range(n)]

def bfs():
	que=deque([])
	que.append(0)
	D[0]=0
	while que:
		p=que.popleft()
		for np in L[p]:
			if D[np]==float('inf'):
				que.append(np)
				D[np]=p+1

bfs()

if sum(D)==float('inf'):
	print('No')
else:
	print('Yes')
	for i in range(1,n):
		print(D[i])

Submission status: Accepted

Solution code:
import collections

def main():
    n, m = map(int, input().split())
    g = [[] for i 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)
    ans = solve(n, m, g)
    if -1 in ans:
        print('No')
    else:
        print('Yes')
        print(*ans, sep = '\n')


def solve(n, m, g):
    q = collections.deque()
    distances = [-1 for i in range(n)]
    ans  = [-1 for i in range(n)]
    distances[0] = 0
    q.append(0)
    while len(q):
        pos = q.popleft()
        for i in g[pos]:
            if distances[i] == -1:
                q.append(i)
                distances[i] = distances[pos] + 1
                ans[i] = pos + 1
    return ans[1:]


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
import queue

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

guide = {}
room = defaultdict(list)

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


q = queue.Queue()

for i in room[1]:
    q.put(i)
    guide[i] = 1

while not(q.empty()):
    x = q.get()
    for i in room[x]:
        if i not in guide:
            guide[i]=x
            q.put(i)



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

Submission status: Accepted

Solution code:
import queue

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

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

q = queue.Queue()
q.put((1, 0))
while(not q.empty()):
    x, p = q.get()
    if parents[x] != -1:
        continue
    parents[x] = p
    for connection in rooms[x]:
        if parents[connection] == -1:
            q.put((connection, x))
print('Yes')
for p in parents[2:]:
    print(p)

Submission status: Accepted

Solution code:
#D
from queue import Queue
N,M=map(int,input().split())

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

Pas=[0 for i in range(N+1)]
Flag=[True for i in range(N+1)]
Flag[0:2]=[False,False]
st=Queue()
st.put(1)
while not st.empty():
    s=st.get()
    for i in X[s]:
        if Flag[i]:
            Pas[i]=s
            Flag[i]=False
            st.put(i)

result="Yes"
for i in range(2,N+1):
    if Flag[i]:
        result="No"

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

Submission status: Accepted

Solution code:
from collections import defaultdict

N, M = [int(el) for el in input().split()]
paths = defaultdict(lambda: set())

for _ in range(M):
    S, D = [int(el) for el in input().split()]
    paths[S].add(D)
    paths[D].add(S)

post = [0 for _ in range(N + 1)]
post[0] = post[1] = 1
queue = [1, ]
while queue:
    s = queue.pop(0)
    for d in paths[s]:
        if post[d] == 0:
            post[d] = s
            queue.append(d)

if post.count(0) != 0:
    print("No")
else:
    print("Yes")
    for item in post[2:]:
        print(item)