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 = (int(x) for x in input().split())
list_load=[[0] for i in range(n)]
for i in range(m):
    a, b = (int(x) for x in input().split())
    list_load[a-1].append(b)
    list_load[b-1].append(a)
list_ans=[0]*n

que=deque()
que.append(1)
while que:
    now = que.pop()
    for i in list_load[now-1]:
        if i!=0:
            if list_ans[i-1]==0:
                list_ans[i-1]=now
                que.appendleft(i)
bool = True
for i in range(1,n):
    if list_ans[i]==0:
        bool=False
if bool:
    print("Yes")
    for i in range(1,n):
        print(list_ans[i])
else:
    print("No")

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n, m = LI()
G = [[] for _ in range(n)]
for _ in range(m):
    a, b = LI()
    G[a - 1] += [b - 1]
    G[b - 1] += [a - 1]

D = [-1] * n
D[0] = 0
q = deque([0])
while q:
    u = q.popleft()
    for v in G[u]:
        if D[v] == -1:
            D[v] = D[u] + 1
            q += [v]

print('Yes')
for i in range(1, n):
    ret = INF
    for j in G[i]:
        if D[j] < ret:
            ret = D[j]
            ans = j
    print(ans + 1)

Submission status: Accepted

Solution code:
from collections import deque
n,m=map(int,input().split())
g=[[] for i in range(n)]
INF=1001001001
par=[INF for i in range(n)]
par[0]=0
for i in range(m):
  s,t=map(int,input().split())
  g[s-1].append(t-1)
  g[t-1].append(s-1)

q=deque([])
q.append(0)
while q:
  now = q.popleft()
  for i in g[now]:
    if par[i]==INF:
      par[i]=now
      q.append(i)

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

Submission status: Accepted

Solution code:
import sys
import math
import numpy as np
from collections import Counter, defaultdict, deque

input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)


def S():
    return input().rstrip()


def I():
    return int(input())


def MI():
    return map(int, input().split())


inf = float("inf")

n, m = MI()
way = defaultdict(set)
for _ in range(m):
    a, b = MI()
    way[a].add(b)
    way[b].add(a)

passed = [0] * (n + 1)
q = set([1])
while q:
    qq = set()
    for room in q:
        for next in way[room]:
            if not passed[next]:
                passed[next] = room
                qq.add(next)
    q = qq

if all(passed[2:]):
    print("Yes")
    for p in passed[2:]:
        print(p)
else:
    print("No")

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
AB = [list(map(int,input().split())) for i in range(M)]
from collections import deque
from collections import defaultdict
# 各ノードから行ける隣接のーどの辞書

ans = [0]*N

new_AB = []
for ab in AB:
    new_AB.append([ab[0],ab[1]])
    new_AB.append([ab[1],ab[0]])
# AB = [[ab[0],ab[1]] if ab[0] < ab[1] else [ab[1],ab[0]] for ab in AB]

adj = defaultdict(list)

for ab in new_AB:
    adj[ab[0]].append(ab[1])

q = deque()
q.append(1)

# print(adj)
# キューが空になるまで繰り返す
while len(q) > 0:
    # キューの先頭（左端）からnodeを取り出す
    node = q.popleft()
    # print(node)

    for next_node in adj[node]:
        if ans[next_node-1] != 0:
            continue
        ans[next_node-1] = node
        q.append(next_node)


# exit()
print("Yes")
for an in ans[1:]:
    print(an)



# def bfs(depth,)

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
n, m = map(int, input().split())
# a = [0 for i in range(m)]
# b = [0 for i in range(m)]
edge = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    edge[a - 1].append([1, b - 1])
    edge[b - 1].append([1, a - 1])
# print("edge =", edge)
cost = dijkstra_heap(0, edge, n)
# print(cost)
print("Yes")
for i in range(1, n):
    minimum = INF
    ans = None
    for j in edge[i]:
        if cost[j[1]] < minimum:
            minimum = cost[j[1]]
            ans = j[1]
    print(ans + 1)

Submission status: Accepted

Solution code:
from collections import defaultdict
import queue
def dfs(i):
    global count
    if count >= N or ans[i] != 0:
        return
    
    for ii in A2B[i]:
        dfs(ii)
N, M = map(int, input().split())
A2B = defaultdict(list)
ans = [0 for i in range(N+1)] 
# ans[1] = 1
for m in range(M):
    a, b = map(int, input().split())
    A2B[a] += [b]
    A2B[b] += [a]
count = 0
q = queue.Queue()
q.put((1, 1))
while count < N:
    t, f = q.get()
    if ans[t] != 0:
        continue
    count += 1
    ans[t] = f
    for x in A2B[t]:
        q.put((x, t))
print('Yes')
for i in range(2, N+1):
    print(ans[i])

Submission status: Accepted

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

from collections import deque 
def main():
    N, M = map(int, readline().split())
    to = [[]  for _ in range(N)]
    for _ in range(M):
        a, b = map(int, readline().split())
        to[a-1].append(b-1)
        to[b-1].append(a-1) 

    dq = deque()
    dq.append(0)
    done = [0 for _ in range(N)]
    done[0] = 1
    ans = [0 for _ in range(N)]
    while len(dq) > 0:
        v = dq.popleft()
        for nx in to[v]:
            if done[nx]:
                continue
            ans[nx] = v
            done[nx] = 1
            dq.append(nx) 
    print('Yes')
    for i in ans[1:]:
        print(i+1)
if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

from collections import deque

ans = [-1] * n
def bfs(u):
   queue = deque([u])
   d = [None] * n
   d[u] = 0
   while queue:
      v = queue.popleft()
      for i in g[v]:
         if d[i] is None:
            d[i] = d[v] + 1
            queue.append(i)
            ans[i] = v + 1

   return d

d = bfs(0)
ans.pop(0)
if -1 in ans:
   print('No')
else:
   print('Yes')
   for x in ans:
      print(x)

Submission status: Accepted

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

seen = [False]*n
ans = [0]*n
Q = deque()
def f(s):
    Q.append(s)
    seen[s] = True
    while Q:
        now = Q.popleft()
        for nxt in G[now]:
            if seen[nxt]: continue
            ans[nxt] = now+1
            Q.append(nxt)
            seen[nxt] = True
f(0)
print("Yes")
for i in range(1,n): print(ans[i])

Submission status: Accepted

Solution code:
import sys
import copy
import math
import bisect
import pprint
import bisect
from functools import reduce
from copy import deepcopy
from collections import deque
from decimal import *

import numpy as np

import math

def rootCheck(checkList):
    nextList=[]
    for i in checkList:
        for j in root[i]:
            if hint[j] == -1:
                hint[j] = i
                nextList.append(j)
    if len(nextList) >0:
        rootCheck(nextList)



if __name__ == '__main__':
    sys.setrecursionlimit(10 ** 6)
    n, m = map(int, input().split())
    root = {}
    for i in range(m):
        b, c = map(int, input().split())
        if b-1 in root:
            root[b-1].append(c-1)
        else:
            root[b-1]=[c-1]
        if c-1 in root:
            root[c-1].append(b-1)
        else:
            root[c-1]=[b-1]
    hint =[-1]*n

    for i in root[0]:
        if hint[i] == -1:
            hint[i] = 0


    rootCheck(root[0])

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import copy

class Node():
    def __init__(self, index):
        self.index = index
        self.connect = []
        self.michi = None
    
    def add_edge(self, node):
        self.connect.append(node)
    
    def show_connect_node_index(self):
        return [node.index for node in self.connect]
    
    def add_michisirube(self, index):
        self.michi = index


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

for m in range(M):
    A_m, B_m = map(int, input().split())
    node_list[A_m-1].add_edge(node_list[B_m-1])
    node_list[B_m-1].add_edge(node_list[A_m-1])

# 道標追加。Node 1から順に
tansaku_node = [node_list[0]]
while tansaku_node != []:
    new_tansaku_node = []
    for node in tansaku_node:
        for child_node in node.connect:
            if child_node.michi == None:
                child_node.michi = node.index
                new_tansaku_node.append(child_node)
    tansaku_node = new_tansaku_node

print('Yes')
for n in range(1,N):
    print(node_list[n].michi)

Submission status: Accepted

Solution code:
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)
from collections import deque
d = deque([[0,0]]) # 左は今考えてる部屋、右は前の部屋
ans = [-1 for i in range(n)]
kak = [-100 for i in range(n)]
while d:
    u,v = d.popleft()
    if ans[u] == -1:
        ans[u] = v
    for j in g[u]:
        if ans[j] == -1 and kak[j] == -100:
            kak[j] = 0
            d.append([j,u])
        else:
            continue
print('Yes')
for i in range(1,n):
    print(ans[i]+1)

Submission status: Accepted

Solution code:
def main():
    from collections import deque
    n, m, *ab = map(int, open(0).read().split())
    l = [[] for _ in range(n+1)]
    for i, j in zip(*[iter(ab)] * 2):
        l[i].append(j)
        l[j].append(i)

    ll = [0 for _ in range(n+1)]
    vis = [False for _ in range(n+1)]
    que = deque()
    que.append(1)
    vis[1] = True
    while que:
        now = que.popleft()
        nx = l[now]
        for i in nx:
            if vis[i]:
                continue
            vis[i] = True
            ll[i] = now
            que.append(i)
    if all(vis[1:]):
        print("Yes")
        s = "\n".join(map(str, ll[2:]))
        print(s)
    else:
        print("No")



if __name__ == '__main__':
    main()

Submission status: Accepted

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

visited = [0]*(n+1)
#sign = [0]*(n+1)
visited[1] = 1
q = Queue()
q.put(1)
while not q.empty():
	x = q.get()
	rooms = graph[x]
	for r in rooms:
		if visited[r] == 0:
			visited[r] = x
			q.put(r)

possible = True
for i in range(2,n+1):
	if visited[i] == 0:
		possible = False
		break
if possible:
	print("Yes")
	for i in range(2,n+1):
		print(visited[i])
else:
	print("No")

Submission status: Accepted

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

stamp=[-1]*n
queue=deque([0])
while queue:
    d=queue.popleft()
    for i in maze[d]:
        if stamp[i]==-1:
            stamp[i]=d
            queue.append(i)

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

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
INF = 10**10

def dijkstra(n, G, s):
  dist = [INF] * n 
  que = [(0, s)]   
  dist[s] = 0
  last = [[] for _ in range(n)]
    
  while que:
    c, v = heappop(que)
    if dist[v] < c:
      continue
    for t, cost in G[v]: 
      if dist[v] + cost < dist[t]:
        dist[t] = dist[v] + cost
        heappush(que, (dist[t], t))                
        last[t].append(v)                        

  return dist,last

n,m = map(int,input().split())
G = [[]*n for _ in range(n)]
for i in range(m):
  a,b = map(int,input().split())
  G[a-1].append((b-1,1))
  G[b-1].append((a-1,1))
  
ans,last = dijkstra(n,G,0)

if max(ans) > m:
  print('No')
else:
  print('Yes')
  for i in range(1,n):    
    print(last[i][-1]+1)
    pass

Submission status: Accepted

Solution code:
from collections import deque

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

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

list_step = [-1] * N
list_step[0] = 0
queue = deque([0])
while len(queue) > 0:
    parent = queue.popleft()
    for i in range(len(list_road[parent])):
        tmp = list_road[parent][i]
        if list_step[tmp] == -1:
            list_step[tmp] = parent
            queue.append(tmp)

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

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque

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

edges_list = [[] for _ in range(N)]
seen_list = [-1] * N

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

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

while queue:
    current = queue.popleft()
    for n in edges_list[current]:
        if seen_list[n] == -1:
            seen_list[n] = current
            queue.append(n)

if -1 in seen_list:
    print("No")
else:
    print("Yes")
    for i in range(len(seen_list) - 1):
        print(seen_list[i+1] + 1)

Submission status: Accepted

Solution code:
from collections import deque

N, M = map(int, input().split())
con = [[] for _ in range(N)]
for i in range(M):
    A, B = map(int, input().split())
    con[A-1].append(B-1)
    con[B-1].append(A-1)
    
d = deque()
houmon = [False] * N
ans = [0] * (N-1)

houmon[0] = True
d.append(0)
while d:
#     print(d, houmon, ans)
    room = d.popleft()
#     houmon[room] = True
#     print(room)
    
    for next_room in con[room]:
        if not houmon[next_room]:
            ans[next_room-1] = room+1
            d.append(next_room)
            houmon[next_room] = True
    
print('Yes\n' + '\n'.join(map(str, ans)))

Submission status: Accepted

Solution code:
import heapq

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

#print(N, M, path)

hq = [(0, 0, 1)]

mark = [None] * (N + 1)

while hq:
  cost, prev, node = heapq.heappop(hq)
  #print(cost, prev, node)
  if not mark[node]:
    mark[node] = prev
    for nxt in path[node]:
      heapq.heappush(hq, (cost + 1, node, nxt))

if all(mark[2:]):
  print('Yes')
  for m in mark[2:]:
    print(m)
else:
  print('No')

Submission status: Accepted

Solution code:
from collections import deque
import heapq
class Graph:
    edges = {}

    def append_edge(self, sv, ev, weight = 1):
        if sv in self.edges:
            self.edges[sv].append((ev, weight))
        else:
            self.edges[sv] = [(ev, weight)]

    def bfs(self, sv, n):
        dist = [-1]*len(self.edges.keys())
        q = deque([])   # キュー
        q.append(sv)
        dist[sv] = 0
        connect_vtxs = []
        ans = [-1] * n
        ans[0] = -1
        while len(q) > 0:
            p = q.popleft()     # キュー取りだし（先頭）
            connect_vtxs.append(p)
            for (ev, w) in self.edges[p]:
                if ans[ev] == -1:
                    ans[ev] = p
                if dist[ev] != -1:
                    continue
                q.append(ev)    # キュー追加
                dist[ev] = dist[p] + 1
        return ans


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

for i in range(len(ab)):
    ab[i][0] -= 1
    ab[i][1] -= 1

g = Graph()
for i in range(M):
    s = ab[i][0]
    t = ab[i][1]
    g.append_edge(s, t)
    g.append_edge(t, s)

ans = g.bfs(0, N)
ans = ans[1:]

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

Submission status: Accepted

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

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

L=[-1]*N
L[0]=0
tmp=[0]
while tmp:
    T0=tmp.pop(0)
    
    for j in S[T0]:
        if L[j]==-1:
            L[j]=T0
            tmp.append(j)

label=True
for j in L:
    if L==-1:
        label=False
if label:
    print('Yes')
    for j in L[1:]:
        print(j+1)
else:
    print('No')

Submission status: Accepted

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

for _ in range(m):
  p,q = map(int,input().split())
  ls[p].append(q)
  ls[q].append(p)
ans = [None]*(n+1)

cur = 1
que = [1]
count = 1
while que:
  cur = que.pop(0)
  for v in ls[cur]:
    if ans[v] == None:
      ans[v] = cur
      que.append(v)
      

print("Yes")
for s in ans[2:]:
  print(s)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
a = [0 for _ in range(m)]
b = [0 for _ in range(m)]

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

ans = [-1 for _ in range(n-1)]
looked = [1 for _ in range(n)]
queue = [0]
looked[0] = 0
can = [[] for _ in range(n)]

for i in range(m):
    can[a[i]].append(b[i])
    can[b[i]].append(a[i])

while(len(queue)):
    now = queue.pop(0)
    for i in can[now]:
        if looked[i]:
            queue.append(i)
            looked[i] = 0
            ans[i-1] = now+1
for i in ans:
    if ans == -1:
        print("No")
        exit
print("Yes")
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

from collections import deque
    
N, M = mi()
#U = UnionFind(N)
rel = [[] for _ in range(N)]

mark = [-1]*N
flag = [0]*N
mark[0] = 0
l = deque([0])
'''
def dfs(s):
    print(mark)
    if rel[s]:
        for num in rel[s]:
            if mark[num] == -1:
                mark[num] = s
        for num in rel[s]:
            if rel[num]:
                dfs(num)   
'''
for i in range(M):
    s, t = mi()
    s -= 1
    t -= 1
    rel[s].append(t)
    rel[t].append(s)

#dfs(0)
flag[0] = 1
while l != deque([]):
    a = l.popleft()
    for num in rel[a]:
        if not flag[num]:
            mark[num] = a
            flag[num] = 1
            l.append(num)

if sum(flag) != N:
    print('No')
    exit()
print('Yes')
for i in range(1, N):
    print(mark[i]+1)

Submission status: Accepted

Solution code:
# ABC168d


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    # 再帰関数を使わない限りPypyで出すこと

    def dump(*args):
        sys.stderr.write(str(args))
    from collections import deque
    INF = 10**12

    import heapq
    import sys

    input = sys.stdin.readline

    def dijkstra_heap(s, edge, n):
        # 始点sから各頂点への最短距離
        d = [INF] * n
        used = [True] * n  # True:未確定
        d[s] = 0
        used[s] = False
        edgelist = []
        frm = [-1]*n
        for a, b in edge[s]:
            heapq.heappush(edgelist, (a*(10**6)+b, -1))
        while len(edgelist):
            minedge = heapq.heappop(edgelist)
            froom = minedge[1]
            minedge = minedge[0]
            # まだ使われてない頂点の中から最小の距離のものを探す
            if not used[minedge % (10**6)]:
                continue
            v = minedge % (10**6)
            d[v] = minedge // (10 ** 6)
            frm[v] = froom
            used[v] = False
            for e in edge[v]:
                if used[e[1]]:
                    heapq.heappush(edgelist, ((e[0]+d[v])*(10**6)+e[1], v))
        return (d, frm)

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

    dist = dijkstra_heap(0, edges, n)
    #print(dist[0], dist[1])
   # print(graph.dist)
    # print(graph.frm)
    if INF in dist[0]:
        print('No')
        exit(0)
    print('Yes')
    for i in dist[1][1:]:
        print(i+1 if i+1 != 0 else 1)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

E = {}
for i in range(N):
  E[i] = set()
  
for i in range(M):
  a,b = list(map(int, input().split()))
  a,b = a-1, b-1
  E[a].add(b)
  E[b].add(a)
  
visited = [False] * N
will_search = [False] * N
q = deque()
q.append(0)
ans = [0] * N
while len(q) >0:
  now = q.popleft()
  visited[now] = True
  for x in E[now]:
    if visited[x] or will_search[x]:
      continue
    will_search[x] = True
    ans[x] = now
    q.append(x)
    
if len(ans) < N:
  print('No')
else:
  print('Yes')
  for a in ans[1:]:
    print(a+1)

Submission status: Accepted

Solution code:
from collections import deque

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

visited = [False] * n
q = deque()
q.append((0, -1))
ans = [0] * n

while q:
    v, pv = q.popleft()
    ans[v] = pv+1
    for nv in g[v]:
        if visited[nv]: continue
        visited[nv] = True
        q.append((nv, v))

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

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())

    g[a-1].append(b-1)
    g[b-1].append(a-1)

d = [-1] * n
d[0] = 0
b = [[] for _ in range(n)]
q = deque([0])
while q:
    v = q.popleft()
    for e in g[v]:
        if d[e] == -1:
            d[e] = d[v] + 1
            b[e].append(v)
            q.append(e)

if -1 in d:
    print("No")
else:
    print("Yes")
    for i in range(1, n):
        print(b[i][0]+1)

Submission status: Accepted

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

queue = deque()
seen = [-1] * N
steps = [-1] * N
steps[0] = 0
parents = [-1] * N
queue.append(0)
while queue:
    node = queue.popleft()

    seen[node] = 1
    #print("now: "+str(node))
    for next in graph[node]:
        if seen[next] > -1:
            continue
        #print("next: " + str(next))
        queue.append(next)
        seen[next] = 1
        steps[next] = steps[node] + 1
        parents[next] = node

print("Yes")
for a in parents[1:]:
    print(a+1)

Submission status: Accepted

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

edge = [[] for _ in range(n)]
for a, b in ab:
    edge[a].append(b)
    edge[b].append(a)

visited = [False]*n
visited[0] = True
dq = deque([0])
ans = [-1]*n

while dq:
    now = dq.popleft()
    for e in edge[now]:
        if visited[e]==False:
            visited[e] = True
            dq.append(e)
            ans[e]=now

f = True
for a in ans[1:]:
    if a == -1: f = False
if not f:
    print('No')
else:
    print('Yes')
    for a in ans[1:]:
        print(a+1)

Submission status: Accepted

Solution code:
from collections import defaultdict,deque

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

dist = [None]*N
q = deque()

s = 1  # スタート
q.append(s)
dist[s-1] = 0

while len(q)!=0:
    From = q.popleft()
    for To in d[From]:
        if dist[To-1] == None:
            q.append(To)
            dist[To-1] = From


if None in dist:
    print("No")
else:
    print("Yes")
    for i in range(1,N):
        print(dist[i])