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: Wrong Answer

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()
for i in ['Yes']+gr.dfs(0)[1:]:
    show(i)

Submission status: Wrong Answer

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'
 
    while queue:
        v = queue.popleft() # 'v'に探索候補のノードを popleft
        for i in pic[v]: # pic[v]: 探索候補のノードに隣接するノードのリスト
            if dis[i] is None:
                dis[i] = dis[v] + 1 # 'u'からの距離を記録
                queue.append(i)
    return dis[1:]

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

Submission status: Wrong Answer

Solution code:
def main():
    from collections import deque
    import sys

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

    an=[0]*(n-1)
    tg = deque([1])
    wwk =deque([])
    while not(all(an)):
        while len(tg):
            itg = tg.pop()
            for j in abl[itg-1]:
                if an[j-2]==0:
                    an[j-2]=itg
                    wwk.append(j)
                if all(an):
                    print('Yes')
                    for j in an:
                        print(j)
                    sys.exit()
        tg=deque(wwk)
        wwk =deque([])

    if all(an):
        print('Yes')
        for j in an:
            print(j)
    else:
        print('No')

main()

Submission status: Wrong Answer

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)

print(memo)

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: Wrong Answer

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())
    memo[a].append(b)
    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: Wrong Answer

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] = dist[v] + 1
    d.append(i)
    
ans = dist[1:]
if all(d == -1 for d in dist):
  print('No')
  exit()
print('Yes')
for i in range(1,len(ans)):
  print(ans[i])

Submission status: Wrong Answer

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)
mark = [0]*(N+1)

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

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

Submission status: Wrong Answer

Solution code:
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 = [1]
check = [0]*(N+1)
mark = [0]*(N+1)

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

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

Submission status: Wrong Answer

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())
    g[a-1].append(b-1)
    g[b-1].append(a-1)
q = [0]
dist = [-1]*n
dist[0] = 0
pre = [0]*n
while q != []:
    v = q.pop()
    for t in g[v]:
        if dist[t] == -1:
            dist[t] = dist[v] + 1
            pre[t] = v
            q.append(t)
print('Yes')
for i in range(1, n):
    print(pre[i]+1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = map(int,input().split())
cnct = [[] for i in range(N+1)]
for _ in range(M):
  A,B = map(int,input().split())
  cnct[A].append(B)
  cnct[B].append(A)
Q = deque()
Q.append(1)
ans = [0]*(N+1)
vstd = [0]*(N+1)
while Q:
  temp = Q.popleft()
  for a in cnct[temp]:
    if vstd[a] == 0:
      ans[a] = temp
      vstd[a] = 1
      Q.append(a)
for a in ans[2:]:
  print(a)

Submission status: Wrong Answer

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

list_a = []
list_b = []

for i in range(m):
    a, b = map(int, input().split())
    list_a.append(a)
    list_b.append(b)

room_signpost = [0] * n


def recursive(a_list, b_list, rooms):
    next_rooms = []
    for room in rooms:

        roomindexes_a = [idx for idx, val in enumerate(a_list) if val == room]
        roomindexes_b = [idx for idx, val in enumerate(b_list) if val == room]

        for i in roomindexes_a:
            next_rooms.append(b_list[i])
            if room_signpost[b_list[i] - 1] == 0:
                room_signpost[b_list[i] - 1] = room
            else:
                pass
        for i in roomindexes_b:
            next_rooms.append(a_list[i])
            if room_signpost[a_list[i] - 1] == 0:
                room_signpost[a_list[i] - 1] = room
            else:
                pass

        del_index = sorted(roomindexes_a + roomindexes_b, reverse=True)

        for idx in del_index:
            del a_list[idx]
            del b_list[idx]

        print(a_list)
        print(b_list)
        print(next_rooms)

    if not next_rooms:
        return
    else:
        recursive(a_list, b_list, next_rooms)

recursive(list_a, list_b, [1])

room_signpost[0] = "Yes"
for row in room_signpost:
    print(row)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    from collections import deque
    from sys import stdin
    readline = stdin.readline

    n,m = map(int, readline().split())
    abl =[[]for i in range(n)]
    for i in range(m):
        a,b = map(int,readline().split())
        abl[a-1].append(b)
        abl[b-1].append(a)
    
    an=[0]*(n-1)
    i=1
    wk=deque([i])
    wwk=deque([])
    il=deque(abl[0])

    while any(wk):
        i=wk.pop()
        il=deque(abl[i-1])
        lil=len(il)
        for k in range(lil):
            iwk=il.pop()
            if an[iwk-2]==0:
                wwk.append(iwk)
                an[iwk-2]=i
                if all(an):
                    print('Yes')
                    for i in an:
                        print(i)
                    sys.exit()
        if not(any(wk)):
            wk=deque(wwk)
            wwk=deque([])
    print('No')

main()

Submission status: Wrong Answer

Solution code:
#from statistics import median
import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
#from fractions import gcd
#from itertools import combinations # (string,3) 3回
#from collections import deque
#from collections import deque,defaultdict
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n,m = readInts()
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)
D = [-1] * n
D[0] = 0
def bfs(pre):
    nya = False
    for v in G[pre]:
        if D[v] < 0:
            D[v] = pre + 1
            nya = True
    if nya:
        bfs(v)
bfs(0)
if -1 in D:
    print('No')
else:
    print('Yes')
    print(*D[1:],sep='\n')

Submission status: Wrong Answer

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

done=[False for i in range(n)]
ans=[-1 for i in range(n)]
def bfs():
  que=[0]

  while(que):
    now=que.pop(0)
    done[now]=True
    for i in l[now]:
      if done[i]==False:
        que.append(i)
        done[i]=True
        ans[i]=now+1
bfs()
print(*ans[1:])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
def IL(): return map(int,sys.stdin.readline().rstrip().split())

def BFS(n,m,table,dist,next):
    if not -1 in dist:   return True
    for i in range(len(next)):
        tmp = next[i]
        nnext = []
        for j in range(n):
            if table[tmp][j]:
                table[tmp][j] = table[j][tmp] = 0
                if dist[j]==-1:
                    dist[j] = tmp+1
                else:
                    dist[j] = min(dist[j],tmp+1)
                nnext.append(j)
    if 0<len(nnext):
        return BFS(n,m,table,dist,nnext)
    return  False

def main():
    n,m = IL()
    table = [[0]*n for _ in range(n)]
    for _ in range(m):
        a,b = IL()
        table[a-1][b-1] = table[b-1][a-1] = 1
    dist = [-1]*n
    dist[0] = 0
    if BFS(n,m,table,dist,[0]):
        print('Yes')
        for i in range(1,len(dist)):
            print(dist[i])
    else:  print('No')
    return

if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
def IL(): return map(int,sys.stdin.readline().rstrip().split())

def BFS(n,m,table,dist,next):
    if not -1 in dist:   return True
    for i in range(len(next)):
        tmp = next[i]
        nnext = []
        for j in range(n):
            if dist[j]==-1:
                if table[tmp][j]:
                    table[tmp][j] = table[j][tmp] = 0
                    dist[j] = tmp+1
                    nnext.append(j)
    if 0<len(nnext):
        return BFS(n,m,table,dist,nnext)
    return  False

def main():
    n,m = IL()
    table = [[0]*n for _ in range(n)]
    for _ in range(m):
        a,b = IL()
        table[a-1][b-1] = table[b-1][a-1] = 1
    dist = [-1]*n
    dist[0] = 0
    if BFS(n,m,table,dist,[0]):
        print('Yes')
        for i in range(1,len(dist)):
            print(dist[i])
    else:  print('No')
    
        
    return

if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys 
sys.setrecursionlimit(10**6)
def S(): return sys.stdin.readline().rstrip()
def SL(): return map(str,sys.stdin.readline().rstrip().split())
def I(): return int(sys.stdin.readline().rstrip())
def IL(): return map(int,sys.stdin.readline().rstrip().split())
def LS(): return list(sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))

def BFS(n,m,table,dist,next):
    if not -1 in dist:   return
    for i in range(len(next)):
        tmp = next[i]
        nnext = []
        for j in range(n):
            if table[tmp][j] and dist[j]==-1:
                table[tmp][j] = table[j][tmp] = 0
                dist[j] = tmp+1
                nnext.append(j)
    if 0<len(nnext):
        BFS(n,m,table,dist,nnext)
    return

def main():
    n,m = IL()
    table = [[0]*n for _ in range(n)]
    for _ in range(m):
        a,b = IL()
        table[a-1][b-1] = table[b-1][a-1] = 1
    dist = [-1]*n
    dist[0] = 0
    BFS(n,m,table,dist,[0])
    if -1 in dist:  print('No')
    else:
        print('Yes')
        for i in range(1,len(dist)):
            print(dist[i])
    return

if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
P = [list(map(int,input().split())) for i in range(m)]
minimum=[0]+[n]*(n-1)
answer=[0]*(n-1)
for i in range(n):
  for j in range(m):
    if minimum[P[j][0]-1]==i:
      if(minimum[P[j][1]-1]>i+1):
        minimum[P[j][1]-1]=i+1
        answer[P[j][1]-2]=P[j][0]
    if minimum[P[j][1]-1]==i:
      if(minimum[P[j][0]-1]>i+1):
        minimum[P[j][0]-1]=i+1
        answer[P[j][0]-2]=P[j][1]
print("YES")
for i in range(n-1):
  print(answer[i])

Submission status: Wrong Answer

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

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

l = [0]*(n+1)
num = [1]

while num:
    v = num.pop(0)
    for i in lab[v]:
        if not l[i]:
            l[i] = v
            num.append(i)

if not 0 in l:
    print("Yes")
    for i in range(2, n+1):
        print(l[i])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
G = [[] for i in range(N)]
R = [0]*N
for m in range(M):
    A,B = map(int, input().split())
    G[A-1].append(B-1)
    G[B-1].append(A-1)
d = deque()
for n in G[0]:
    d.append(n)
    R[n]=1
while len(d)>0:
    i = d.popleft()
    for j in range(len(G[i])):
        if R[G[i][j]] == 0 and G[i][j]!=0:
            d.append(G[i][j])
            R[G[i][j]]=i+1

for n in range(1,N):
    print(R[n])

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m = map(int, input().split())
g = [[] for i in range(n)]
for _ in range(m):
  a, b = map(int, input().split())
  g[b-1].append(a-1)
  g[a-1].append(b-1)
a = [-1]*n
def bfs(n):
  q=deque()
  q.append(n)
  a[n] = 0
  while len(q):
    x=q.popleft()
    for i in g[x]:
      if a[i]==-1: 
        a[i]=a[x]+1
        q.append(i)
bfs(0)
if -1 in a:
  print('No')
else:
  print('Yes')
  for i in a[1:]:
    print(i)

Submission status: Wrong Answer

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

result = []
passed_room = [1]
depth = 1

while paths and depth<N:
  tmp_passed = passed_room.copy()
  
  for i, path in enumerate(paths):
   
    if path[0] in passed_room:
      if path[1] in passed_room:
        del paths[i]
        continue
      result.append((path[1], path[0]))
      tmp_passed.append(path[1])
      del paths[i]
      continue
    
    if path[1] in passed_room:
      if path[0] in passed_room:
        del paths[i]
        continue
      result.append((path[0], path[1]))
      tmp_passed.append(path[0])
      del paths[i]
      continue
  depth += 1
  passed_room  = passed_room + tmp_passed
  if len(tmp_passed) == 0:
    print('No')
    exit()
  
    
result = sorted(result)
print('Yes')
for i, j in result:
  print(j)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    from collections import deque

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

    an=[0]*(n-1)
    i=1
    wk=deque([i])
    wwk=deque([])
    il=deque(abl[0])

    while any(wk):
        i=wk.pop()
        il=deque(abl[i-1])
        for k in range(len(il)):
            iwk=il.pop()
            if an[iwk-2]==0 and iwk>1:
                wwk.append(iwk)
                an[iwk-2]=i
                if all(an):
                    print('Yes')
                    for i in an:
                        print(i)
                    sys.exit()
        if not(any(wk)):
            wk=deque(wwk)
            wwk=deque([])
    print('No')

Submission status: Wrong Answer

Solution code:
from collections import deque

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

#S = [[0 for j in range(3)] for i in range(2)]　2行3列の場合
S = [[]for i in range(N+1)]
D = [-1]*(N+1)
deq=deque()

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

D[1]=0
deq.append(1)
while len(deq)!=0:
    v= deq.popleft()
    
    
    for nv in S[v]:
        if D[nv] !=-1:
            continue
        D[nv] =D[v]+1
        deq.append(nv)
        


for i in range(N):
    if D[N]!=-1:
        continue
    else:
        print("No")
        exit()
print("Yes")
for i in range(2,N+1):
    print(D[i])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
def bfs(v,G,queue,dist):
    dist[0] = 0
    seen[v] = True
    for vertex in G[v]:
        if seen[vertex]:
            continue
        elif vertex in queue:
            continue
        queue.append(vertex)
        dist[vertex] = dist[v] + 1
    for elements in queue:
        queue.remove(elements)
        bfs(elements,G,queue,dist)
N,M = map(int,input().split())
dist = [-1 for _ in range(N)]
seen = [False for _ in range(N)]
G = dict()
for i in range(N):
    G[i] = []   
for _ in range(M):
    a,b = map(int,input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)
queue = []
count = 0
ans = []
bfs(0,G,queue,dist)
memo = [0] * (max(dist)+1)
for i in range(max(dist)+1):
    k = dist.count(i)
    memo[i] = k
for v in range(1,N): 
    if len(G[v]) < memo[dist[v]-1]:
        for el in G[v]: 
            if dist[v] == dist[el] + 1:
                ans.append(el+1)
                count += 1
                break
    else:
        L = [ve for ve in range(len(dist)) if ve == dist[v]-1]
        for el in L:
            if el in G[v]:
                ans.append(el+1)
                count += 1
                break
    if count != v : 
        print("No")
        sys.exit(0)
print("Yes")
for el in ans:
    print(el)