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
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,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 RA():return map(int,open(0).read().split())
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 accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
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 YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

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)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.node_size=len(ls)+1
                self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.node_size=int(input())
        else:
            self.node_size=inp_size
        self.edges,_=GI(self.node_size,self.node_size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.node_size=len(ls)+1
        self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.node_size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.node_size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.node_size
        self.ETout=[-1]*self.node_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.st=SegTree(self.node_size*2-1,self.ETdepth,function=min,ide=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]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in edge]) for edge in self.edges]):
            print( [[nd for nd,d in edge] for edge in self.edges] )
        else:
            print(self)
 
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
    
    # return boundary index of r such that func({table[i]} =< x , i in [pos,r]
    def right_bound(self,pos,x):
        k=(self.size-pos).bit_length()
        for j in range(k)[::-1]:
            nx=pos+(1<<j)
            if nx<n and self.query(pos,nx+1)<=x:
                pos+=(1<<j)
        return pos
    
    # return boundary index of l such that func({table[i]} =< x , i in [l,pos]
    def left_bound(self,pos,x):
        k=pos.bit_length()
        for j in range(k)[::-1]:
            nx=pos-(1<<j)
            if 0<=nx and self.query(nx,pos+1)<=x:
                pos-=(1<<j)
        return pos
 
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)


show_flg=False
show_flg=True
ans=0


class Graph:
    def __init__(self,inp_node_size=None,inp_edge_size=None,ls=None,init=True,Directed=False,index=1):
        if init:
            if ls==None:
                self.stdin(inp_node_size,inp_edge_size,Directed=Directed,index=index)
            else:
                self.listin(ls,Directed=Directed,index=index)
        else:
            self.edges=[]
        return
 
    def stdin(self,inp_node_size=None,inp_edge_size=None,Directed=False,index=1):
        if (inp_node_size,inp_edge_size)==(None,None):
            self.node_size,self.edge_size=LI()
            self.edges,_=GI(self.node_size,self.edge_size,Directed=Directed,index=index)
        else:
            self.node_size=inp_node_size
            self.edge_size=inp_edge_size
            self.edges,_=GI(self.node_size,self.edge_size,Directed=Directed,index=index)
        return
    
    def listin(self,inp_node_size,ls,Directed=False,index=0):
        self.node_size=inp_node_size
        self.edge_size=len(ls)
        self.edges,_=GI(self.node_size,self.edge_size,ls,Directed=Directed,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v

    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.node_size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps

    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in edge]) for edge in self.edges]):
            print( [[nd for nd,d in edge] for edge in self.edges] )
        else:
            print(self)

gr=Graph(init=False)
'''
n,m=LI()
ls=[]
for i in rep(m):
    ls+=[LI_()]

#gr.listin(n,ls,index=0,Directed=True)
v=gr.dfs(0)
'''

gr=Graph()
v=gr.bfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)

show('Yes')
for i in v[1:]:
    show(i+1)

Submission status: Accepted

Solution code:
# ダミーノード'0'を設定 ※※※
# AtCoder Beginner Contest 168
# https://atcoder.jp/contests/abc168/tasks/abc168_d

import sys
input = sys.stdin.readline

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

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

from collections import deque

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

print('Yes')

tmp = BFS(1) # ここは開始位置'1'

for j in tmp[2:]:
    print(j) # ※※※

Submission status: Accepted

Solution code:
#幅優先探索(BFS)
import sys
input = sys.stdin.readline

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

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

from collections import deque
di= [0]*n
def bfs(u):
    queue = deque([u])
    d = [None] * n # uからの距離の初期化
    d[u] = 0 # 自分との距離は0
    while queue:
        v = queue.popleft()
        for i in g[v]:
            if d[i] is None:
                d[i] = d[v] + 1
                di[i] = v
                queue.append(i)
    return d

# 0からの各頂点の距離
d = bfs(0)
print("Yes")
for i in range(1,n):
    print(di[i]+1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

"""
N rooms
M paths

0 room is start
"""
class UnionFind():
    # 作りたい要素数nで初期化
    # 使用するインスタンス変数の初期化
    def __init__(self, n):
        self.n = n
        # root[x]<0ならそのノードが根かつその値が木の要素数
        # rootノードでその木の要素数を記録する
        self.root = [-1]*(n+1)
        # 木をくっつける時にアンバランスにならないように調整する
        self.rnk = [0]*(n+1)

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

N, M = LI()
AB = []
for i in range(M):
    a,b = LI()
    a -= 1
    b -= 1
    AB.append((a,b))

paths = {}
for i in range(N):
    paths[i] = []
for a, b in AB:
    paths[a].append(b)
    paths[b].append(a)

# uf = UnionFind(N)
# for a,b in AB:
#     uf.Unite(a,b)

# ans = True
# for i in range(N):
#     if not uf.isSameGroup(0, i):
#         ans = False

# if ans == False:
#     print("No")
#     sys.exit()

q = collections.deque()

# node No, parent No
q.append((0, -1))

anss = [0 for i in range(N)]
rooms = [0 for i in range(N)]
rooms[0] = 1
while len(q) > 0:
    node, p = q.popleft()

    for path in paths[node]:
        if path == p:
            continue
        if rooms[path]: # すでに探索済み
            continue
        q.append((path, node))
        rooms[path] = 1
        anss[path] = node
print("Yes")
for ans in anss[1:]:
    print(ans + 1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

"""
N rooms
M paths

0 room is start
"""
class UnionFind():
    # 作りたい要素数nで初期化
    # 使用するインスタンス変数の初期化
    def __init__(self, n):
        self.n = n
        # root[x]<0ならそのノードが根かつその値が木の要素数
        # rootノードでその木の要素数を記録する
        self.root = [-1]*(n+1)
        # 木をくっつける時にアンバランスにならないように調整する
        self.rnk = [0]*(n+1)

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

N, M = LI()
AB = []
for i in range(M):
    a,b = LI()
    a -= 1
    b -= 1
    AB.append((a,b))

paths = {}
for i in range(N):
    paths[i] = []
for a, b in AB:
    paths[a].append(b)
    paths[b].append(a)

uf = UnionFind(N)
for a,b in AB:
    uf.Unite(a,b)

ans = True
for i in range(N):
    if not uf.isSameGroup(0, i):
        ans = False

if ans == False:
    print("No")
    sys.exit()

q = collections.deque()

# node No, parent No
q.append((0, -1))

anss = [0 for i in range(N)]
rooms = [0 for i in range(N)]
rooms[0] = 1
while len(q) > 0:
    node, p = q.popleft()

    for path in paths[node]:
        if path == p:
            continue
        if rooms[path]: # すでに探索済み
            continue
        q.append((path, node))
        rooms[path] = 1
        anss[path] = node
print("Yes")
for ans in anss[1:]:
    print(ans + 1)

Submission status: Accepted

Solution code:
from collections import deque

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

queue = deque()
landmarks[1] = 0
queue.append(1)
while len(queue) != 0:
  v = queue.popleft()
  for i in edges[v]:
    if landmarks[i] != -1:
      continue
    landmarks[i] = v
    queue.append(i)
flag = 1
for i in range(2,n+1):
  if landmarks[i] == -1:
    flag = 0
if flag:
  print('Yes')
  for i in range(2,n+1):
    print(landmarks[i])
else:
  print('No')

Submission status: Accepted

Solution code:
import sys
import time
st = time.perf_counter()
# ------------------------------

from collections import deque

N, M = map(int, input().split())
graph = [[] for i in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)
D = deque([0])
visited = [False] * N
visited[0] = True
sirusi = [0] * N
while D:
    d = D.popleft()
    for i in graph[d]:
        if visited[i]: continue
        visited[i] = True
        D.append(i)
        sirusi[i] = d
print('Yes')
for i in range(1, N):
    print(sirusi[i] + 1)
    
# ------------------------------
ed = time.perf_counter()
print('time:', ed-st, file=sys.stderr)

Submission status: Accepted

Solution code:
from collections import deque

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

def LI():
    return list(map(int, input().split()))

N, M = MI()
room = [[] for _ in range(N)]

for _ in range(M):
    A, B = MI()
    room[A - 1].append(B - 1)
    room[B - 1].append(A - 1)

ans = [-1] * N
queue = deque([0])

while queue:
    u = queue.popleft()
    
    for r in room[u]:
        if ans[r] == -1:
            ans[r] = u + 1
            queue.append(r)

print("Yes")

for a in ans[1:]:
    print(a)

Submission status: Accepted

Solution code:
from collections import deque

n, m = map(int, input().split())
graph = [[] for _ in range(n)]
sign = [-1] * n
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    graph[a].append(b)
    graph[b].append(a)
D = deque([0])
visited = [False]*n
visited[0] = True
while D:
    v=D.popleft()
    for j in graph[v]:
        if visited[j]:
            continue
        visited[j] = True
        sign[j] = v
        D.append(j)

print("Yes")
for k in range(1, n):
    print(sign[k]+1)

Submission status: Accepted

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

memo = [[] for _ in range(n+1)]

for i in range(m):
    a, b = map(int, input().split())
    if b != 1:
        memo[a].append(b)
    if a != 1:
        memo[b].append(a)
        
signs = [-1] * (n+1)

now = [1]
cnt = 1
while cnt < n:
    next = []
    for j in now:
        roots = memo[j]
        for k in roots:
            if signs[k] == -1:
                signs[k] = j
                next.append(k)
                cnt += 1
    now = next[:]

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

Submission status: Accepted

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

graph = [[] for _ in range(n+1)]

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


dist = [-1] * (n+1)
dist[0] = 0
dist[1] = 0

from collections import deque
d = deque()
d.append(1)

while d:
  v = d.popleft()
  
  for i in graph[v]:
    if dist[i] != -1:
      continue
    dist[i] = v
    d.append(i)
    
ans = dist[2:]
if all(d == -1 for d in dist):
  print('No')
  exit()
print('Yes')
for i in range(len(ans)):
  print(ans[i])

Submission status: Accepted

Solution code:
from collections import deque

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

D=deque([])
D.append(0)
visit=[False]*n
visit[0]=True

while D:
    v=D.popleft()
    for i in x[v]:
        if visit[i]:continue
        visit[i]=True
        cnt[i]=v
        D.append(i)
print("Yes")
for i in range(1,n):
    print(cnt[i]+1)

Submission status: Accepted

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


queue = deque([1])

depth = [-1]*(n+1)

depth[0] = depth[1] = 0

ans = [-1]*(n+1)

while queue:
    v = queue.popleft()
    for i in path[v]:
        if depth[i] == -1:
            depth[i] = depth[v] + 1
            queue.append(i)
            ans[i] = v

if -1 in depth:
    print("No")
else:
    print("Yes")
    # for i in range(2, n+1):
    #     print("部屋番号：", i, "path", path[i])
    #     print("深さ", depth[i])
    print(*ans[2:], sep="\n")

Submission status: Accepted

Solution code:
from collections import defaultdict
from queue import Queue
g = defaultdict(list)
visted = defaultdict(bool)
N, M = map(int, input().split())
for i in range(M):
    A, B = map(int, input().split())
    g[A].append(B)
    g[B].append(A)

h = [-1] * (N+1)

h2 = defaultdict(list)
def solve(v):
    visited = set()
    q = Queue()
    visited.add(v)
    h[v] = 0
    h2[0].append(v)
    q.put(v)
    while not q.empty():
        v = q.get()
        for c in g[v]:
            if not c in visited:
                visited.add(c)
                h[c] = h[v] + 1
                h2[h[v]+1].append(c)
                q.put(c)

solve(1)
ans = []

for v in range(2, N+1):
    i = h[v]

    for c in g[v]:
        if h[c] == i-1:
            ans.append(c)
            break


print('Yes')
for v in ans:
    print(v)

Submission status: Accepted

Solution code:
import math
import sys
from collections import deque
import heapq
import copy
import itertools
from itertools import permutations
from itertools import combinations
import bisect
def mi() : return map(int,sys.stdin.readline().split())
def ii() : return int(sys.stdin.readline().rstrip())
def i() : return sys.stdin.readline().rstrip()
a,b=mi()
l=[[] for i in range(a)]
for j in range(b):
  x,y=mi()
  l[x-1].append(y-1)
  l[y-1].append(x-1)
lst=[-1]*a
q=deque([0])
while q:
  s=q.popleft()
  for j in l[s]:
    if lst[j]==-1:
      lst[j]=s
      q.append(j)
print("Yes")
for k in range(a-1):
  print(lst[k+1]+1)

Submission status: Accepted

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

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

from collections import deque

def bfs(Que, Dist, L, Root):    
    while Que:
        x = Que.popleft()
        d = Dist[x]
        
        for l in L[x]:
            new_x = l
            if Dist[new_x] == -1:
                Dist[new_x] = d + 1
                Root[new_x] = x
                Que.append(new_x)
    return Dist, Root
    
Que = deque()
Dist = [-1 for _ in range(N+1)]
Root = [-1 for _ in range(N+1)]

Que.append(1)
Dist[1] = 0
Dist, Root = bfs(Que, Dist, L, Root)

More0 = [r > 0 for r in Root[2:]] 
Is1 = [r == 1 for r in Root[2:]]

if all(More0) and any(Is1):
    print('Yes')
    print('\n'.join(map(str, Root[2:])))
else:
    print('No')

Submission status: Accepted

Solution code:
from collections import deque

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

for a, b in AB:
  g[a].append(b)
  g[b].append(a)

d = deque([1])
l = [0]*(N+1)
while d:
  r = d.popleft()
  for s in g[r]:
    if l[s] == 0:
      d.append(s)
      l[s] = r

print("Yes", *l[2:], sep="\n")

Submission status: Accepted

Solution code:
import queue
N, M = map(int, input().split())
adj = [[]for i in range(N+1)]
parent = [-1] * (N+1)  # -1なら未訪問
for m in range(M):
    a, b = map(int, input().split())
    adj[a].append(b)
    adj[b].append(a)
q = queue.Queue()  # 自分の部屋番号、親の部屋番号
q.put((1, 0))  # 部屋1の親は部屋0と考える
while(not q.empty()):
    x, p = q.get()
    if parent[x] != -1:  # 訪問済み
        continue
    parent[x] = p
    for next in adj[x]:
        if parent[next] == -1:  # 未訪問なら
            q.put((next, x))  # 探索候補に追加
print('Yes')  # 必ず目標は達成できる
for p in parent[2:]:  # 部屋2以降の親（前の部屋）
    print(p)

Submission status: Accepted

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

ans = 'No'
st = deque([1])
check = [0]*(N+1)
check[1] = 1
mark = [0]*(N+1)

while st:
  s = st.popleft()
  for t in l[s]:
    if check[t] == 0:
      mark[t] = s
      check[t] = 1
      st.append(t)
if sum(check) == N:
  ans = 'Yes'

print(ans)
if ans == 'Yes':
  for i in range(2,N+1):
    print(mark[i])

Submission status: Accepted

Solution code:
import networkx as nx
N, M = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(M)]
 
G = nx.Graph()
G.add_nodes_from(range(1, N+1))
G.add_edges_from(l)
pre = nx.predecessor(G, 1)

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

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)
q = deque([0])
pre = [-1 for _ in range(n)]
while q:
    v = q.popleft()
    for t in g[v]:
        if pre[t] == -1:
            pre[t] = v
            q.append(t)
print('Yes')
for i in range(1, n):
    print(pre[i]+1)

Submission status: Accepted

Solution code:
import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
from math import cos,sin,tan,sqrt
import cmath as cma
import copy as cp
import sys
import re
sys.setrecursionlimit(10**7)
EPS = sys.float_info.epsilon
PI = np.pi; EXP = np.e; INF = np.inf
MOD = 10**9 + 7

def sinput(): return sys.stdin.readline().strip()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(n=0):
    if n: return [0 for _ in range(n)]
    else: return list(imap())
def farr(): return list(fmap())
def sarr(n=0):
    if n: return ["" for _ in range(n)]
    else: return sinput().split()
def barr(n): return [False for _ in range(n)]
def adj(n): return [[] for _ in range(n)]

n,m = imap()
ab = np.array([iarr() for i in range(m)])
g = adj(n+1)
for i in range(m):
    aa,bb = ab[i][0],ab[i][1]
    g[aa].append(bb)
    g[bb].append(aa)

dep = iarr(n+1)
dep[1] = 1
q = col.deque([1])
route = iarr(n+1)
while q:
    now = q.popleft()
    for next in g[now]:
        if dep[next]: continue
        else:
            q.append(next)
            dep[next] = dep[now]+1
            route[next] = now

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