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,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()
 
class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def __str__(self):
        return  str(self.edges)
 
    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)
 
class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]
 
    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

def dijkstra(edge,st):
    # edge=[[(v_to,dist_to_v),...],[],...]
    # initialize: def: d=dist(st,i), prev=[previous vertex in minimum path], q[]
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    prev=[0]*n
    q=[(j,i) for i,j in enumerate(d)]
    heapify(q)
    v=[False]*n
    # calc
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for dst,dist in edge[cur]:
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                prev[dst]=cur
                heappush(q,(alt,dst))
    return d,prev


show_flg=False
show_flg=True
ans=0

n,m=LI()
g,_=GI(n,m)
d,p=dijkstra(g,0)

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

Submission status: Accepted

Solution code:
import math
import numpy as np
import queue
from collections import deque
import heapq

n,m = map(int,input().split())
way = [[] 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)

q = queue.Queue()
q.put(1)
t = [10**18 for i in range(n+1)]
tmt = [-1 for i in range(n+1)]
t[0] = 10*18
t[1] = 0

while not q.empty():
    qi = q.get()
    for i in way[qi]:
        if t[i] > t[qi]+1:
            t[i] = t[qi]+1
            tmt[i] = qi
            q.put(i)

if 10**18 in t:
    print("No")
else:
    print("Yes")
    for i in range(2,n+1):
        print(tmt[i])

Submission status: Accepted

Solution code:
import queue
from collections import defaultdict
n,m = map(int,input().split())
g = defaultdict(set)
ans = [0]*n
for _ in range(m):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    g[a].add(b)
    g[b].add(a)

visited = [False]*n
visited[0] = True
q = queue.Queue()
q.put(0)
while not q.empty():
    v = q.get()
    for p in g[v]:
        if not visited[p]:
            ans[p] = v
            q.put(p)
            visited[p] = True
print('Yes')
for x in ans[1:]:
    print(x+1)

Submission status: Accepted

Solution code:
import heapq as hq

def D_stra(N,connections,st):
    mxc=2**29
    cost =[mxc for i in range(N)]
    visited =[False for i in range(N)]
    flx = [mxc for i in range(N)]
    cost[st]=0
    q=[]

    hq.heappush(q,(0,st))

    while q:
        c,node=hq.heappop(q)
        if visited[node]:
            continue
        visited[node]=True

        for connection in connections[node]:
            target,mc=connection
            if cost[target]>c+mc:
                cost[target]=c+mc
                hq.heappush(q,(c+mc,target))
                flx[target]=node
    
    return cost,flx


    

def resolve():
    N,M = map(int,input().split())

    connections = [[] for i in range(N)]
    for i in range(M):
        a,b = map(int,input().split())
        connections[a-1].append([b-1,1])
        connections[b-1].append([a-1,1])
    ans,ans2 = D_stra(N,connections,0)

    if 2**29 in ans:
        print("No")
        return
    print("Yes")
    for i in ans2[1:]:
        print(i+1)

resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from queue import Queue

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)

used = [-1] * n
q = Queue()
used[0] = 0
q.put(0)
while not q.empty():
    s = q.get()
    for t in g[s]:
        if used[t] != -1:
            continue
        used[t] = s
        q.put(t)

if any(x == -1 for x in used):
    print("No")
    exit()

print("Yes")
for x in used[1:]:
    print(x + 1)

Submission status: Accepted

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

q = deque([(1,0)])
ans = [-1]*(N+1)
while q:
    u,v = q.popleft()
    if ans[u] == -1:
        ans[u] = v
        for w in g[u]:
            if w==v:
                continue
            q.append((w,u))

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

Submission status: Accepted

Solution code:
# Graph
import heapq
INF = 10**18

def dijkstra(start, G):
    done = [False]*(len(G))
    dist = [INF]*(len(G))
    dist[start] = 0
    fr = [0]*N
    h = []
    heapq.heappush(h, [0, start])
    while h:
        _, cur = heapq.heappop(h)
        if done[cur]: continue
        done[cur] = True
        for to, cost in G[cur]:
            if dist[cur]+cost < dist[to]:
                dist[to] = dist[cur]+cost
                fr[to] = cur
                heapq.heappush(h, [dist[to], to])
    return fr, dist

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, 1))
    G[b].append((a, 1))
ans, dis = dijkstra(0, G)
print("Yes")
for i in range(1, N):
    print(ans[i]+1)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")



n,m = map(int, input().split())
from collections import defaultdict
ns = defaultdict(set)

for i in range(m):
    u,v = map(int, input().split())
    u -= 1 
    v -= 1
    ns[u].add(v)
    ns[v].add(u)

from queue import deque
start = 0
q = deque([start])
seen = [None] * n
seen[start] = 0
while q:
    u = q.pop()
    d = seen[u]
    for v in ns[u]:
        if seen[v] is None:
            seen[v] = u
            q.appendleft(v)
print("Yes")
print("\n".join(map(lambda x:str(x+1), seen[1:])))

Submission status: Accepted

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

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

es=[[] for _ in range(n)] # es[i] = (頂点iの(隣接する頂点,コスト)の組)
d = [INF]*n # 頂点sからの最短距離
prev=[-1]*n # 経路復元

# 入力
for i in range(m):
    a,b = map(int,input().split())
    a,b = a-1, b-1
    es[a].append((b,1))
    es[b].append((a,1)) # 無向グラフ


def dijkstra(s):
    v = -1
    que = [(0,s)]
    heapify(que)
    d[s] = 0
    while que:
        p = heappop(que)
        v = p[1]
        if d[v] < p[0]:
            continue
        for e in es[v]:
            if d[e[0]] > d[v] + e[1]:
                d[e[0]] = d[v] + e[1]
                heappush(que, (d[e[0]], e[0])) 
                prev[e[0]] = v
def get_path(t):
    path = []
    while t != -1:
        path.append(t)
        t = prev[t]
    path.reverse()
    return path
dijkstra(0)
print("Yes")
for i in range(1,n):
    print(prev[i]+1)

Submission status: Accepted

Solution code:
from collections import deque
N,M = map(int, input().split())
dic = [[] for i in range(N+1)]
for i in range(M):
  a,b = map(int, input().split())
  dic[a].append(b)
  dic[b].append(a)
ans = [-1]*(N+1)
ans[1] = 0
q = deque([1])
while q:
  p = q.popleft()
  for v in dic[p]:
    if ans[v]==-1:
      ans[v] = p
      q.append(v)
if all(-1!=c for c in ans[1:]):
  print('Yes')
  for i in range(2,N+1):
    print(ans[i])
else:
  print('No')

Submission status: Accepted

Solution code:
from collections import deque

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

ans = [-1] * n
q = deque([(0, -2)])
while q:
    v, p = q.popleft()
    if ans[v] != -1:
        continue
    ans[v] = p
    for u in links[v]:
        if ans[u] != -1:
            continue
        q.append((u, v))

print('Yes')
print('\n'.join(str(v + 1) for v in ans[1:]))

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

n,m = map(int,readline().split())
data = list(map(int,read().split()))
it = iter(data)

links = [[] for _ in range(n+1)]
for a,b in zip(it,it):
    links[a].append(b)
    links[b].append(a)

d = deque()
d.append(1)
parent = [-1] * (n+1)
parent[1] = 0

while(d):
    i = d.popleft()
    for j in links[i]:
        if(parent[j] == -1):
            parent[j] = i
            d.append(j)

ans = parent[2:]
if(min(ans) == -1):
    print('No')
else:
    print('Yes')
    print('\n'.join(map(str,ans)))

Submission status: Accepted

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

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

pre = defaultdict(int)
pre[1] = 0
d = [10**6]*(N+1)

dq = deque([1])
d[1] = 0

while dq:
    v = dq.popleft()
    for nv in g[v]:
        if d[v] + 1 < d[nv]:
            d[nv] = d[v] + 1
            pre[nv] = v
            dq.append(nv)

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import sys
sys.setrecursionlimit(10**9)
from collections import deque
import heapq
from itertools import combinations
import bisect

n,m=map(int,input().split())
g=[[] for i in range(n)]
for i in range(m):
    a,b=map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)
q=deque([0])
ans=[-1]*n
ans[0]=0
while q:
    p=q.popleft()
    for i in g[p]:
        if ans[i]==-1:
            ans[i]=p+1
            q.append(i)
ans=ans[1:]
print('Yes')
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6) #再帰関数の上限
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque 
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする


def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)



def tree_init(N,M):
    edgelist = [[] for _ in range(N)]
    for a, b in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
        edgelist[a-1].append(b-1)#ノードの番号が0から始まる場合-1を消す
        edgelist[b-1].append(a-1)
    return edgelist

def dfs(N, start, edge):
    q=deque([(start,0)])
    visited=[False]*N
    ans=[0]*N
    while len(q):
        e, pe=q.popleft()#ここをpopleftにすると幅優先探索BFSになる
        if visited[e]:continue
        ans[e]=pe
        visited[e]=True
        for ne in edge[e]:
            q.append((ne,e))
            
    return ans

def main():
    mod = 10**9+7
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列

    edgelist=tree_init(N,M)

    ans=dfs(N,0,edgelist)
    print('Yes')
    for a in ans[1:]:
        print(a+1)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop


def dijkstra(graph: list, n: int, v_s: int, INF: int = float('inf')) -> list:
    # graph[v_from] = [(cost, v_to), ...]
    dist = [INF] * n
    prev_node = [-1] * n

    dist[v_s] = 0
    heap = [(0, v_s)]  # heap = [(dist[v], v), ...]
    while heap:
        dist2v, v_from = heappop(heap)
        if dist[v_from] < dist2v:
            continue
        for cost, v_to in graph[v_from]:
            dist_cand = dist2v + cost
            if dist_cand < dist[v_to]:
                dist[v_to] = dist_cand
                prev_node[v_to] = v_from
                heappush(heap, (dist[v_to], v_to))
    return dist, prev_node


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

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

dist, prev_node = dijkstra(graph, n, 0)
# print(dist)
# print(prev_node)

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

Submission status: Accepted

Solution code:
def Int():
    return int(input())
def Ints():
    return map(int,input().split())
def IntList():
    return list(Ints())
def IntMat(N):
    return [IntList() for i in range(N)]

import sys
sys.setrecursionlimit(4100000)
input = sys.stdin.readline

N,M = Ints()

from collections import defaultdict
Graph = defaultdict(list)

for i in range(M):     #ABC = [now, to, cost] のリストを想定
    A,B = Ints()
    Graph[A].append([B,1])
    Graph[B].append([A,1])

def dijkstra_heap(s,Graph,N):
    import heapq
    que = []
    INF = 10**18
    MIN = [INF]*(N+1)    #N: 頂点数, 1,Nの場合も考慮してる
    From = [-1]*(N+1)
    
    heapq.heappush(que,[0,s])

    while que != []:
        nowc,to = heapq.heappop(que)
        MIN[to] = min(nowc, MIN[to])
        if MIN[to] >= nowc:
            for (b,c) in Graph[to]:
                if nowc+c < MIN[b]:
                    From[b] = to
                    MIN[b] = nowc+c
                    heapq.heappush(que,[nowc+c,b])
    return MIN,From

MIN,From = dijkstra_heap(1,Graph,N+1)

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

Submission status: Accepted

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

def bfs():
    q = deque([0])
    dist = [-1]*N
    dist[0] = 0
    ans = [-1]*N
    
    while q:
        v = q.popleft()
        
        for nv in G[v]:
            if dist[nv]==-1:
                ans[nv] = v
                dist[nv] = dist[v]+1
                q.append(nv)
    
    return ans

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)

ans = bfs()
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())
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)

visited = [False]*n
d = [10**15]*n

visited[0] = True
d[0] = 0
q = deque([0])

ans = [0]*n

while q:
    v = q.popleft()
    for w in g[v]:
        if not visited[w]:
            visited[w] = True
            d[w] = d[v] + 1
            ans[w] = v+1
            q.append(w)

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

Submission status: Accepted

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

adj = [list() for _ in range(N)]

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

parent = [None]*N
queue = deque([0])
while queue:
    u = queue.popleft()
    for v in adj[u]:
        if parent[v] is None:
            parent[v] = u
            queue.append(v)

print('Yes')
print(*(x+1 for x in parent[1:]), sep='\n')

Submission status: Accepted

Solution code:
#グラフの連結成分を調べる
def Graph(ab):
    G=[[] for i in range(n)]
    for a,b in ab:
        G[a-1].append(b)
        G[b-1].append(a)
    return G
#BFS
from collections import deque
def bfs(G):
    q=deque()
    q.append((1, -1))
    log = [0] * n
    log[0] = 1
    while q:
        #qの先頭を取り出す
        V, P = q.popleft()
        for new_v in G[V - 1]:
            if new_v == P:continue
            if log[new_v - 1] != 0:continue
            log[new_v - 1] = V
            q.append((new_v, V))

    return log



n, m = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(m)]
G = Graph(ab)
log = bfs(G)
print('Yes')
print(*log[1:], sep='\n')

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations, combinations_with_replacement
from heapq import heappop, heappush
from fractions import gcd
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])


def main():
    n,m = inpm()
    g = [[] for _ in range(n)]
    for _ in range(m):
        a,b = inpm()
        a -= 1
        b -= 1
        g[a].append(b)
        g[b].append(a)
    did = [0 for _ in range(n)]
    did[0] = 1
    que = deque()
    que.append(0)
    ans = [0 for _ in range(n-1)]
    while que:
        next_que = deque()
        while que:
            go = que.pop()
            for i in range(len(g[go])):
                if did[g[go][i]]:
                    continue
                ans[g[go][i]-1] = go + 1
                did[g[go][i]] = 1
                next_que.append(g[go][i])
        que = next_que
    if 0 in ans:
        print('No')
        return
    print('Yes')
    for i in range(n-1):
        print(ans[i])

if __name__ == "__main__":
    main()

Submission status: Accepted

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

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi

MOD = 10 ** 9 + 7
INF = 10 ** 18

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

graph = [[] for _ in range(N + 1)]
arrow = [0] * (N + 1)

for a, b in AB:
    graph[a].append(b)
    graph[b].append(a)
    
def bfs(st, graph):
    INF = 10 ** 18
    dist = [0] * len(graph)
    dist[st] = 1
    queue = deque([st])
    while queue:
        q = queue.popleft()
        for r in graph[q]:
            if dist[r] == 0:
                dist[r] = q
                queue.append(r)
    return dist

answer = bfs(1, graph)[2:]
print("Yes")
for a in answer:
    print(a)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


def yes():
    print("Yes")  # type: str


import heapq
from collections import defaultdict


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = defaultdict(list)

    def add_edge(self, s, t, w=1):
        self.E[s].append((t, w))
        self.E[t].append((s, w))


def shortestPath(g: Graph, s: int):
    # 返り値 (dist, prev)
    # dist: 始点からの距離が格納されたリスト
    # prev: 始点から最短経路で移動する場合、各頂点に至る前の頂点のリスト
    dist = [INF]*g.N
    dist[s] = 0

    prev = [None]*g.N
    Q = []
    heapq.heappush(Q, (dist[s], s))

    while len(Q) > 0:
        _, u = heapq.heappop(Q)
        for v, w in g.E[u]:
            if dist[v] > dist[u] + w:
                dist[v] = dist[u] + w
                prev[v] = u
                heapq.heappush(Q, (dist[v], v))
    return dist, prev


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):

    g = Graph(N)
    for a, b in zip(A, B):
        g.add_edge(a-1, b-1)

    dist, prev = shortestPath(g, 0)
    if dist == INF:
        print("No")
        return
    print("Yes")
    for i in range(1, N):
        print(prev[i]+1)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
ab = [list(map(int, input().split())) for _i in range(m)]

visit = [-1 for _ in range(n)]
visit[0] = 0
tree = [[] for _ in range(n)]
for a, b in ab:
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

from collections import deque
q = deque([0])
while q:
    p = q.popleft()
    for i in tree[p]:
        if visit[i] < 0:
            visit[i] = p
            q.append(i)
if all(i >= 0 for i in visit):
    print("Yes")
    for i in visit[1:]:
        print(i+1)
else:
    print("No")

Submission status: Accepted

Solution code:
import collections
def main():

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

    visited = dict()
    cur = [1]
    while cur:
        temp = []
        for v in cur:
            for u in graph[v]:
                if u not in visited:
                    visited[u] = v
                    temp.append(u)
        cur = temp

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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

N, M = map(int, input().split())
edge = [[] for _ in range(N + 1)]
for _ in range(M):
    x, y = map(int, input().split())
    edge[x].append(y)
    edge[y].append(x)

prev = [None] * (N + 1)
seen = [False] * (N + 1)
node = deque([1])
seen[1] = True

while node:
    s = node.popleft()
    for t in edge[s]:
        if not seen[t]:
            seen[t] = True
            prev[t] = s
            node.append(t)

if any(x is None for x in prev[2:]):
    print("No")
else:
    print("Yes")
    print(*prev[2:], sep="\n")