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

INF = float('inf')

N, M = list(map(int, input().split()))
d = {i: [] for i in range(N)}

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

queue = collections.deque()
queue.append((0, 0))
results = {i: (INF, -1) for i in range(N)}
results[0] = (0, 0)
used = set()

while queue:
    cost, cur = queue.pop()
    if cur in used:
        continue
    used.add(cur)
    next_list = d[cur]

    for next_cur in next_list:
        next_cost = cost+1
        if next_cost < results[next_cur][0]:
            results[next_cur] = (next_cost, cur)
            queue.appendleft((next_cost, next_cur))

is_no = False
for k, result in results.items():
    if k == 0:
        continue
    if result[1] == -1:
        is_no = True

if is_no:
    print('No')
else:
    print('Yes')
    for k, result in results.items():
        if k == 0:
            continue
        print(result[1] + 1)

Submission status: Accepted

Solution code:
from collections import deque

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

dist = [1000000] * n
ans = [None]*n
not_visited = set(range(n))
not_visited.remove(0)
vs = deque([0])
dist[0] = 0
while vs:
    v = vs.popleft()
    for other_side in e[v]:
        if other_side in not_visited:
            vs.append(other_side)
            not_visited.remove(other_side)
            if dist[other_side] > dist[v] + 1:
                dist[other_side] = dist[v] + 1
                ans[other_side] = v

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

Submission status: Accepted

Solution code:
import collections,copy,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N,M = LI()
AB = [LI() for _ in range(M)]
graph = {i:collections.deque() for i in range(1,N+1)} #1_indexed
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)
seen = [0]*(N+1) #1_indexed
min_dist = [-1]*(N+1) #1_indexed
queue = collections.deque() #部屋NOを入れておく
def bfs():
    c_graph = copy.deepcopy(graph)
    seen[1] = 1
    queue.append(1)
    min_dist[1] = 0
    while queue:
        q_NO = queue.popleft()
        q_dist = min_dist[q_NO]
        if not c_graph[q_NO]:
            continue
        g = c_graph[q_NO]
        for _ in range(len(g)):
            g_NO = g.popleft()
            if seen[g_NO]:
                continue
            seen[g_NO] = 1
            queue.append(g_NO)
            min_dist[g_NO] = q_dist+1
bfs()
if not all(seen[2:]):
    print('No')
    exit()
print('Yes')
for j in range(2,N+1):
    ans,dist = 0,float('INF')
    for x in graph[j]:
        if dist>=min_dist[x]:
            ans = x
            dist = min_dist[x]
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque


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

ab_list = [list(map(int,input().split())) for _ in range(m)]

ab_count = {key:[] for key in range(1,n+1)}

for i in range(m):
    ab_count[ab_list[i][0]].append(ab_list[i][1])
    ab_count[ab_list[i][1]].append(ab_list[i][0])


#print(ab_count)

que = deque()

#始点は1、階層は0からスタート
que.append([1,0])

checked_dict = {key:[] for key in range(1,n+1)}
#temp_dict = {key:[] for key in range(1,n+1)}
where = 0

while que:
    x_pop = que.popleft()
    x = x_pop[0]
    if where != x_pop[1]:
        pass
        ##階層が代わったから、temp_dictをchecked_dictへ反映させる処理
        #for k in range(1,n+1):
        #    if len(checked_dict[k]) == 0:
        #        checked_dict[k] = temp_dict[k]
        #    else:
        #        aaa = set(checked_dict[k]) & set(temp_dict[k])
        #        if aaa != set():
        #            checked_dict[k] = list(aaa)

    where = x_pop[1]

    for j in ab_count[x]:
        if len(checked_dict[j]) == 0:
            #OK,temp_dictに入れて、queに入れる。
            #temp_dict[j].append(x)
            checked_dict[j].append(x)
            que.append([j,where+1])
        else:
            continue

    

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

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
from collections import defaultdict
AB_dict = defaultdict(list)
dist_list = [-1] * N
dist_list[0] = 0
pre_list = []
for _ in range(M):
    a, b = [int(i)-1 for i in input().split()]
    AB_dict[a].append(b)
    AB_dict[b].append(a)
    if a == 0:
        pre_list.append(b)
        dist_list[b] = 0
    if b == 0:
        pre_list.append(a)
        dist_list[a] = 0
#print(AB_dict)

    
while True:
    tmp = []
    #print(pre_list)
    for p in pre_list:
        #print(p)
        for node in AB_dict[p]:
            #print("node", node)
            if dist_list[node] == -1:
                #print(node, "=", p)
                dist_list[node] = p
                tmp.append(node)
    if tmp == []:
        break
    pre_list = tmp
    
if -1 in dist_list:
    print('No')
    exit()
    
print('Yes')
for dist in dist_list[1:]:
    print(dist+1)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N, M = map(int, sysread().split())
    to = [[] for _ in range(N+1)]
    AB = list(map(int, read().split()))
    A = AB[::2]
    B = AB[1::2]
    for a,b in zip(A,B):
        to[a].append(b)
        to[b].append(a)

    seen = [False] * (N+1)
    queue = deque([])
    seen[1] = True
    queue.append((1, 0))# (node, prev)
    mark = [0] * (N+1)

    while queue:
        current, prev = queue.popleft()
        for next in to[current]:
            if not seen[next]:
                queue.append((next, current))
                mark[next] = current
                seen[next] = True

    print('Yes')
    mark = [str(val) for val in mark]
    print('\n'.join(mark[2:]))

if __name__ == "__main__":
    run()

Submission status: Accepted

Solution code:
n,m = map(int, input().split())
G = {i:[] for i in range(1, n+1)}

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

ans = [-1 for _ in range(n+1)]
ans[0]=1
ans[1]=1
check_list = [1]

while check_list:
  n = check_list.pop(0)
  for g_i in G[n]:
    if ans[g_i]==-1:
      ans[g_i]=n
      check_list.append(g_i)

flg = 'Yes'
if -1 in ans:
  flg = 'No'

if flg=='Yes':
  print('Yes')
  for ans_i in ans[2:]:
    print(ans_i)
else:
  print('No')

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
g = [[] for _ in range(N)]

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

ans_list = [-1] * N

queue = [0]
seen = [False]*N

while queue:
    qi = queue.pop(0)
    # qi から 1 遠い頂点が gi
    for gi in g[qi]:
        if seen[gi] == False:
            queue.append(gi)
            if ans_list[gi] == -1:
                ans_list[gi] = qi
                seen[gi] = True

print("Yes")
for ans in ans_list[1:]:
    print(ans+1)  # 1-index に直す

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def main():
    from collections import deque as d
    N, M = map(int, readline().split())
    m = map(int, read().split())
    AB = zip(m, m)
    graph = [[] for _ in range(N + 1)]
    for a, b in AB:
        graph[a].append(b)
        graph[b].append(a)
    que = d([1])
    ans = [0]*(N+1)
    while que:
        x = d.popleft(que)
        for i in graph[x]:
            if ans[i] != 0:
                continue
            ans[i] = x
            que.append(i)
    for a in ans[2:]:
        if a == 0:
            print('No')
            break
    else:
        print('Yes')
        print('\n'.join(map(str, ans[2:])))

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

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

def main():
    n,m=map(int,input().split())
    graph=[[] for _ in range(n)]
    seen=[False]*n

    for _ in range(m):
        a,b=map(int,input().split())
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    ans=[-1]*n
    q=deque([0])
    seen[0]=True
    while len(q):
        now=q.popleft()
        for i in graph[now]:
            if seen[i]:
                continue
            seen[i]=True
            q.append(i)
            if ans[i]==-1:
                ans[i]=now
    print("Yes")
    for i in range(1,n):
        print(ans[i]+1)

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
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-1)
    d[b-1].append(a-1)

ans = [-1]*n
ans[0] = 0
from collections import deque
q = deque([0])
while q:
    u = q.popleft()
    for v in d[u]:
        if ans[v]==-1:
            ans[v] = u
            q.append(v)
print('Yes')
for i in ans[1:]:
    print(i+1)

Submission status: Accepted

Solution code:
import collections
def solve(a, b, ab_list):

    route = {}

    for a, b in ab_list:
        if a not in route:
            route[a] = []
        if b not in route:
            route[b] = []

        route[a].append(b)
        route[b].append(a)

    deque = collections.deque()
    deque.extend(route[1])
    route_memo = {i:1 for i in route[1]}
    while len(deque) > 0:
        room = deque.popleft()
        for i in route[room]:
            if i != 1 and i not in route_memo:
                route_memo[i] = room
                deque.append(i)

    if len(route_memo.keys()) == n-1:
        print("Yes")
        tmp = sorted(route_memo.items())
        for i in tmp:
            print(i[1])
    else:
        print("No")

if __name__ == "__main__":
    n, m = [int(i) for i in input().split()]
    ab_list = [[int(i) for i in input().split()] for j in range(m)]
    solve(n, m, ab_list)

Submission status: Accepted

Solution code:
import queue

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

parent = [-1] * (n-1)
visit = ["yet"]*(n)
visit[0] = "done"
q = queue.Queue()
q.put(1)
while not q.empty():
    temp = q.get()
    for i in routs[temp]:
        if visit[i-1] == "yet":
            q.put(i)
            if parent[i-2] == -1:
                parent[i-2] = temp
            visit[i-1] = "done"

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

Submission status: Accepted

Solution code:
from collections import deque
n, m = map(int, input().split())
way = [[] for i in range(n + 1)]
ans = [-1 for i in range(n + 1)]
reached = [0 for i in range(n + 1)]

for i in range(m):
    a, b = map(int, input().split())
    way[a].append(b)
    way[b].append(a)
    
D = deque([1])
while D:
    go = D.popleft()
    for i in way[go]:
        if reached[i] == 0:
            D.append(i)
            reached[i] = 1
            ans[i] = go
print("Yes")
for i in range(2, n + 1):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict as d, deque

def bfs(adj, start, n):
	visited = [0] * (n + 1)
	tab = [0] * n
	q = deque([start])
	visited[start] = 1
	while q:
		s = q.popleft()
		for i in adj[s]:
			if visited[i] == 0:
				q.append(i)
				visited[i] = 1
				tab[i - 1] = s
	return tab

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

t = bfs(adj, 1, n)
if 0 in t[1:]:
	print('No')
else:
	print('Yes')
	for i in range(1, n):
		print(t[i])

Submission status: Accepted

Solution code:
from collections import defaultdict
n,m = map(int,input().split())
graph = defaultdict(list)
for i in range(m):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)

ans = defaultdict(int)
next_list = []
for j in graph[1]:
    ans[j] = 1
    next_list.append(j)

target_list = next_list[:]
while True:
    next_list = []
    if len(target_list) == 0:
        break

    for i in target_list:
        for j in graph[i]:
            if j not in ans:
                ans[j] = i
                next_list.append(j)
    target_list = next_list[:]


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())
a  = []
b = [[] for _ in range(n)]
for i in range(m):
    a.append(list(map(int, input().split())))
    

for i in range(m):
    b[a[i][0]-1].append(a[i][1])
    b[a[i][1]-1].append(a[i][0])

seen = [-1]*n
seen[0] = 1
que = deque([1])
while que:
    v = que.popleft()
    for i in b[v-1]:
        if seen[i-1] != -1:
            continue
        que.append(i)
        seen[i-1] = v

for i in range(n):
    if seen[i] == -1:
        print("No")
else:
    del seen[0]
    print("Yes")
    for i in range(n-1):
        print(seen[i])

Submission status: Accepted

Solution code:
from collections import deque
n, m = map(int, input().split())
way = [[] for i in range(n + 1)]
ans = [-1 for i in range(n + 1)]
reached = [0 for i in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    way[a].append(b)
    way[b].append(a)
D = deque([1])
while D:
    go = D.popleft()
    for i in way[go]:
        if reached[i] == 0:
            D.append(i)
            reached[i] = 1
            ans[i] = go
print('Yes')
for i in range(2, n + 1):
    print(ans[i])

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
from heapq import heappop,heappush 

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

mark=[-1]*(N-1)

inf=float("inf")

di=[inf]*N
di[0]=0
hq=[(0,0)]

while hq:
    t,r=heappop(hq) #time room
    if t>di[r]:
        continue
    for x in graph[r]:
        t_new=t+1
        r_new=x
        if t_new<di[r_new]:
            di[r_new]=t_new
            heappush(hq,(t_new,r_new))
            if mark[r_new-1]==-1:
                mark[r_new-1]=r
    
print("Yes")
for i in mark:
    print(i+1)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
n, m = map(int, input().split())
li = [[] for _ in range(n)]
check = [-1] * (n)
check[0] = 0
que = deque([1])
memo = defaultdict(int)
for i in range(m):
    a, b = map(int, input().split())
    li[a-1].append(b)
    li[b-1].append(a)
while que:
    now = que.popleft()
    for l in li[now-1]:
        if check[l-1] != -1: continue
        check[l-1] = now
        que.append(l)

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

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque


def bfs(si):
    q = deque()
    lights = [None for _ in range(N)]
    q.append(si)
    lights[si] = 0

    while len(q) > 0:
        prv_i = q.popleft()
        for i in g[prv_i]:
            if lights[i] is not None:
                continue
            else:
                lights[i] = prv_i
                q.append(i)
    return lights


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

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

lights = bfs(0)
if None in lights:
    print('No')
else:
    print('Yes')
    [print(val + 1) for val in lights[1:]]

Submission status: Accepted

Solution code:
import heapq

max_v,m = input().split()
max_v = int(max_v)
m = int(m)

class Edge(object):
	def __init__(self, to, cost):
		self.to = to
		self.cost = cost


edges = [[] for j in range(max_v)]
for i in range(m):
  a, b = input().split()
  a = int(a)
  b = int(b)
  edges[a-1].append(Edge(b-1,1))
  edges[b-1].append(Edge(a-1,1))

d = [float("inf")]*max_v
fire = [-1]*max_v
#fire = [[[]for j in range(max_v)] for i in range(max_v)]
def dijkstra(s):
	h = []
	d[s] = 0
	heapq.heappush(h, [0,0])
	while(len(h) != 0):
		p = heapq.heappop(h)
		v = p[1]
		if d[v] < p[0]:continue
		for i in range(len(edges[v])):
			e = edges[v][i]
			if d[e.to] > d[v] + e.cost:
				d[e.to] = d[v] + e.cost
				heapq.heappush(h, [d[e.to], e.to])
				fire[e.to] = v
dijkstra(0)
if 2 <= fire.count(-1):
  print("No")
else:
  print("Yes")
  for i in range(1, max_v):
    print(fire[i]+1)

Submission status: Accepted

Solution code:
def LI():return list(map(int,input().split()))
def yes():print("Yes")
def no():print("No")
from collections import deque

def main():
    n,m=LI()
    edge=[[] for i in range(n)]
    for i in range(m):
        a,b=LI()
        a-=1;b-=1
        edge[a].append(b)
        edge[b].append(a)
    
    ans=[-1]*(n)
    goal=deque([0])
    while goal:
        g=goal.popleft()
        for i in edge[g]:
            if ans[i]==-1:
                ans[i]=g+1
                goal.append(i)
    yes()
    print(*ans[1:])
main()

Submission status: Accepted

Solution code:
import sys
import heapq

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)#番号を修正。0スタートに。
#print(g)

INF = float('inf')
reach = [INF for _ in range(N)] #0からの距離を記録。INF未到達。
reach[0] = 0
par = [-1 for _ in range(N)] #親の位置を記録

Q =[]
heapq.heappush(Q, (0,0)) #0からの距離と頂点を入れる。

while Q:
  d,v = heapq.heappop(Q)
  for i in range(len(g[v])): #点vから行ける点をすべて探索
    u = g[v][i] #今探索している点
    #print(v,u)
    if u == 0: #始点の場合はスルー
      continue
    if reach[u] != INF: #到達済みならスキップ
      continue
    reach[u] = d + 1 #探索中の点の到達を記録。
    par[u] = v
    heapq.heappush(Q, (reach[u],u))

#print(reach,par)
if INF not in reach[1:]:
  print("Yes")
  for i in range(1,N):
    ans = par[i]+1
    print(ans)
else:
  print("No")

Submission status: Accepted

Solution code:
def LI():return list(map(int,input().split()))
def yes():print("Yes")
def no():print("No")
from collections import deque

def main():
    n,m=LI()
    edge=[[]*n for i in range(n)]
    for i in range(m):
        a,b=LI()
        a-=1;b-=1
        edge[a].append(b)
        edge[b].append(a)
    
    ans=[-1]*(n)
    goal=deque([0])
    while goal:
        g=goal.popleft()
        for i in edge[g]:
            if ans[i]==-1:
                ans[i]=g+1
                goal.append(i)
    yes()
    print(*ans[1:])
main()

Submission status: Accepted

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

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

D = {} # 親；子
T = {}
for i in range(1, N+1):
    D[i] = []
    T[i] = 0

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

parent = [1]


while len(parent) > 0:
    child = []
    for p in parent:
        for c in D[p]:
            if T[c] != 0: continue
            T[c] = p
            child.append(c)
    parent = child

for i in range(2, N+1):
    if T[i] == 0:
        print('No')
        exit()

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

Submission status: Accepted

Solution code:
import collections,copy,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N,M = LI()
AB = [LI() for _ in range(M)]
graph = {i:collections.deque() for i in range(1,N+1)} #1_indexed
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)
for i in range(1,N+1):
    if not graph[i]:
        print('No')
        exit()
else:
    print('Yes')
seen = [0]*(N+1) #1_indexed
min_dist = [-1]*(N+1) #1_indexed
queue = collections.deque() #頂点NOを入れておく
def bfs():
    c_graph = copy.deepcopy(graph)
    seen[1] = 1
    queue.append(1)
    min_dist[1] = 0
    while queue:
        q_NO = queue.popleft()
        q_dist = min_dist[q_NO]
        if not c_graph[q_NO]:
            continue
        g = c_graph[q_NO]
        for _ in range(len(g)):
            g_NO = g.popleft()
            if seen[g_NO]:
                continue
            seen[g_NO] = 1
            queue.append(g_NO)
            min_dist[g_NO] = q_dist+1
bfs()
for j in range(2,N+1):
    ans,dist = 0,float('INF')
    for x in graph[j]:
        if dist>=min_dist[x]:
            ans = x
            dist = min_dist[x]
    print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    #n = int(input())
    #l = list(map(int, input().split()))
    '''
    A=[]
    B=[]
    for i in range():
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)'''

    n,m = map(int, input().split())
    r=[[]for i in range(n)]
    start = [0, 0]
    #print(bfs(h, w, m, start))
    for i in range(m):
        a,b=map(int, input().split())
        r[a-1].append(b-1)
        r[b-1].append(a-1)
    #print(r)
    
    from collections import deque
    d = [0 for i in range(n)]
    visited=[False for i in range(n)]
    flg = True
    queue=deque([0])
    dd=0
    while queue:
        now=queue.popleft()
        visited[now]=True
        #print(now)
        for i in r[now]:
            if visited[i]:
                continue
            queue.append(i)
            visited[i]=True
            d[i]=now

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


if __name__ == "__main__":
     main()

Submission status: Accepted

Solution code:
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
INF = 10**18

def bfs(start):
    d = [INF]*n
    d[start] = 0
    q = collections.deque([])
    q.append(start)
    pre = [0]*(n)
    while q:
        c = q.popleft()
        next_v = edge[c]
        for v in next_v:
            if v == 0 and start != 0:
                d[v] = d[c]+1
                pre[v] = c
                return [pre,d]
            if d[v] == INF and v != c:
                q.append(v)
                d[v] = d[c]+1
                pre[v] = c
    #経路を復元したい
    return [pre,d]
n,m = map(int,input().split())
edge =[[] for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    a-=1
    b-=1
    edge[a].append(b)
    edge[b].append(a)
ans = bfs(0)
judge = ans[1]
for i in judge:
    if i == INF:
        print("No")
        sys.exit()
print("Yes")
for i in range(1,n):
    print(ans[0][i]+1)

Submission status: Accepted

Solution code:
# coding: utf-8

import sys
import math
import collections
import itertools
import bisect
INF = 10 ** 13
MOD = 10 ** 9 + 7
def input() : return sys.stdin.readline().strip()
def gcd(x, y) : return x if y == 0 else gcd(y, x%y)
def lcm(x, y) : return (x * y) // gcd(x, y)
def I() : return int(input())
def LI() : return [int(x) for x in input().split()]
def RI(N) : return [int(input()) for _ in range(N)]
def LRI(N) : return [[int(x) for x in input().split()] for _ in range(N)]
def LS() : return input().split()
def RS(N) : return [input() for _ in range(N)]
def LRS(N) : return [input().split() for _ in range(N)]
def PL(L) : print(*L, sep="\n")
def YesNo(B) : print("Yes" if B else "No")
def YESNO(B) : print("YES" if B else "NO")

N, M = LI()
AB = LRI(M)

visited = [False] * N

# routeやん
root = [[] for _ in range(N)]
for a, b in AB:
    root[a-1].append(b-1)
    root[b-1].append(a-1)

ret = [-1] * N
Q = collections.deque([[0,0]])
while Q:
    qs = Q.popleft()
    b = qs[0]
    q = qs[1]

    if visited[q]:
        continue
    else:
        visited[q] = True
    
    ret[q] = b

    for r in root[q]:
        Q.append([q, r])

if -1 in ret:
    print("No")
else:
    print("Yes")
    for i, r in enumerate(ret):
        if i == 0:
            continue

        print(r+1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


from heapq import heapify, heappop, heappush, heappushpop


class PriorityQueue:
    def __init__(self, heap):
        '''
        heap ... list
        '''
        self.heap = heap
        heapify(self.heap)

    def push(self, item):
        heappush(self.heap, item)

    def pop(self):
        return heappop(self.heap)

    def pushpop(self, item):
        return heappushpop(self.heap, item)

    def __call__(self):
        return self.heap

    def __len__(self):
        return len(self.heap)


def dijkstra(graph, s, N):
    '''
    graph...隣接リスト形式 リスト内要素は(ノード, エッジ長)
    s...始点ノード
    N...頂点数

    return
    ----------
    D ... 各点までの最短距離
    P ... 最短経路木における親
    '''
    pq = PriorityQueue([])
    P = [None] * N
    D = [float('inf')] * N
    D[s] = 0
    pq.push((D[s], s))  # (最短距離, 次のノード)
    while pq:
        d, v = pq.pop()
        if D[v] < d:  # この辺を扱っても最短距離にならない
            continue  # is_visitedなくてもこれを使うことで最小のものを再び探索するのを防げる
        for to, cost in graph[v]:
            if D[to] > D[v] + cost:  # v周りにおける最短経路の候補の更新
                D[to] = D[v] + cost
                pq.push((D[to], to))
                P[to] = v
    return D, P


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

N, M = read_ints()
# 1から出発したときの最短経路木の親を出力すれば良い
# 必ずYes

graph = defaultdict(lambda: [])
for _ in range(M):
    a, b = read_ints()
    a -= 1
    b -= 1
    graph[a].append((b, 1))
    graph[b].append((a, 1))

D, P = dijkstra(graph, 0, N)
ans = []
for p in P[1:]:
    ans.append(p + 1)
print('Yes')
print(*ans, sep='\n')

Submission status: Accepted

Solution code:
def LI():return list(map(int,input().split()))
def yes():print("Yes")
def no():print("No")
from collections import deque

def main():
    n,m=LI()
    edge=[[] for i in range(n)]
    for i in range(m):
        a,b=LI()
        a-=1;b-=1
        edge[a].append(b)
        edge[b].append(a)    
    ans=[-1]*(n)
    goal=deque([0])
    while goal:
        g=goal.popleft()
        for i in edge[g]:
            if ans[i]==-1:
                ans[i]=g+1
                goal.append(i)
    yes()
    print(*ans[1:])
main()

Submission status: Accepted

Solution code:
import sys
from collections import deque


input = sys.stdin.readline


def main():
    while que:
        nn = que.popleft()
        for n in edges[nn-1]:
            if D[n-1] == INF or D[n-1] > D[nn-1] + 1:
                D[n-1] = D[nn-1] + 1
                que.append(n)
                if n > 1:
                    B[n-2] = nn
    print("Yes")
    for b in B:
        print(b)


if __name__ == "__main__":
    N, M = map(int, input().split())
    edges = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        edges[a-1].append(b)
        edges[b-1].append(a)
    B = [0]*(N-1)
    que = deque([1])
    INF = 10**10
    D = [INF]*N
    D[0] = 0
    main()

Submission status: Accepted

Solution code:
N,M=list(map(int,input().split()))
g=[[] for _ in range(N+1)]#部屋mにつながっている部屋一覧
for m in range(M):
    a,b=list(map(int,input().split()))
    if a<=N and b<=N:
        g[a].append(b)
        g[b].append(a)
queue=[1]
d=[None]*(N+1)
d[0]=0
d[1]=0
while queue:
    v=queue.pop(0)
    for i in g[v]:
        if d[i] is None:
            d[i]=v
            queue.append(i)
for i in range(N+1):
    if d[i] is None:
        print('No')
        exit()
print('Yes')
for i in range(2,N+1):
    print(d[i])