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:
n,m = list(map(int,input().split()))
dist = [[float("inf") for _ in range(n+1)]for _ in range(n+1)]
for i in range(1,n+1):
  dist[i][i] = 0;
for _ in range(m):
  a,b = list(map(int,input().split()))
  dist[a][b] = 1; dist[b][a] = 1;
for k in range(1,n+1):
  for j in range(1,n+1):
    dist[1][j] = min(dist[1][j],dist[1][k] + dist[k][j])
flag = False;
for i in range(2,n+1):
  if dist[1][i] == float("inf"):
    print("NO")
    flag = True
    break;
if not flag:
  print("YES")
  for i in range(2,n+1):
    print(dist[1][i])

Submission status: Wrong Answer

Solution code:
n,edge = map(int,input().split())
l = [0]*n 
stack = [1]
dic  = {}
for i in range (edge) :
    x = [int(x) for x in input().split()]
    if x[0] not in dic :
        dic[x[0]] = []
    if x[1] not in dic :
        dic[x[1]] = []
    dic[x[0]].append(x[1])
    dic[x[1]].append(x[0])
x = 1 
while len(stack) != 0 :
    check = stack[0]
    stack.pop(0)
    for i in range (len(dic[check])) :
        if l[dic[check][i]-1] == 0 :
            x += 1 
            stack.append(dic[check][i])
            l[dic[check][i]-1] = check 
if l.count(0) != 0 :
    print("NO")
else :
    print("YES")
    for i in range (1,n) :
        print(l[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m = map(int,input().split())
l = [list(map(int,input().split())) for _ in range(m)]
# 目印置くリスト
me = [0 for _ in range(n+1)]
me[1] = 1
miti = [[] for _ in range(n+1)]
tansaku = [0 for i in range(n+1)]
tansaku[1]=1
for i,j in l:
  miti[j].append(i)
  miti[i].append(j)
a = deque()
for i in miti[1]:
  a.append(i)
while len(a)!=0:
#  print(a)
  w = a.popleft()
  tansaku[w] = 1
  if 1 in set(miti[w]):
    me[w] = 1
  for j in miti[w]:
    if me[j]==0:
      for t in miti[j]:
        if tansaku[t]==1:
          continue
        else:
          a.append(t) 
      me[j] = w
print("Yes")
for i in range(len(miti)-2):
  print(me[i+2])

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(M)] # nは頂点の数、mは辺の数
G = [[] for _ in range(N)]
A.sort()
for i in range(M):
    a = A[i][0] - 1
    b = A[i][1] - 1
    G[a].append(b)
    G[b].append(a)

from collections import deque

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
                queue.append(i)
    return d

# 0からの各頂点の距離
d = bfs(0)
d = d[1:]
if d.count(None) == 0:
    print("Yes")
    for j in d:
        print(j)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys


def input():
    return sys.stdin.readline()[:-1]


N, M = map(int, input().split())
tree = [[] for i in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    tree[a].append(b)
    tree[b].append(a)
print(tree)
ans = [0]*(N-1)
next_root = [0]
zumi = {}
while True:
    # 次のルートが全部探索済みなら終わり
    for root in next_root:
        if not(root in zumi):
            break
    else:
        break

    tmp_next_root = []
    for root in next_root:
        if root in zumi:
            continue
        for v in tree[root]:
            if v in zumi:
                continue
            if ans[v-1] == 0:
                ans[v-1] = root+1
                tmp_next_root.append(v)
        zumi[root] = True
    next_root = tmp_next_root

if ans.count(0) == 0:
    print('Yes')
    for a in ans:
        print(a)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

n, m = map(int, input().split())
data = []
row = []
col = []
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    data.append(1)
    row.append(a)
    col.append(b)
    data.append(1)
    row.append(b)
    col.append(a)
graph = csr_matrix((data, (row, col)), shape=(n, n))
_, p = shortest_path(graph, return_predecessors=True, directed=False, unweighted=True, indices=0)
for item in p[1:]:
    if(item < 0):
        print("No")
        exit()
for item in p[1:]:
    print(item + 1)

Submission status: Wrong Answer

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


YES = "Yes"  # type: str


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    root = []
    for i in range(N):
        root.append([])
    next = [-1] * N
    for a, b in zip(A, B):
        root[a - 1].append(b - 1)
        root[b - 1].append(a - 1)

    s = set()
    s.add(0)

    while len(s) != 0:
        #print(s)
        #print(next)
        n = s.pop()
        for i in root[n]:
            if next[i] == -1:
                next[i] = n
                if i != 0:
                    s.add(i)


    if -1 in next:
        print("No")
        exit()
    
    print("Yes")
    for i in range(1, len(next)):
        print(next[i] + 1)
    

    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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: Wrong Answer

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

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

b = [1 for i in range(n)]
#フラグ管理

c = []
#キュー

d = [[[10000000 for i in range(n)] for i in range(n)] for i in range(n)]

for x in a:
    d[0][x[0]-1][x[1]-1] = 1
    d[0][x[1]-1][x[0]-1] = 1



for k in range(n-1):
    for i in range(n):
        for j in range(n):
            d[k+1][i][j]=min(d[k][i][j],d[k][i][k]+d[k][k][j])

print('Yes')
for i in range(n-1):
    print(d[n-1][0][i+1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)

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

D = [[] for _ in range(N)]
ANS = [-1] * N


def move(s):
    d = D[s]
    for f in d:
        if ANS[f] != -1:
            return
        ANS[f] = s

    for f in d:
        move(f)


for ab in AB:
    a = ab[0]-1
    b = ab[1]-1

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


move(0)

if -1 not in ANS:
    print('Yes')

for ans in ANS[1:]:
    print(ans+1)

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
data = [[] for _ in range(n)]
for i in range(m):
    ab = list(map(int, input().split()))
    data[ab[0] - 1].append(ab[1] - 1)
    data[ab[1] - 1].append(ab[0] - 1)

d = [float("inf")] * n
que = deque([])
que.append(0)
d[0] = 0

while que:
    p = que.popleft()
    for next in data[p]:
        if d[next] == float("inf"):
            que.append(next)
            d[next] = d[p] + 1

if float("inf") not in d:
    for j in range(n):
        if j == 0:
            print("Yes")
        else:
            print(d[j])
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

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

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

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

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]



def dijkstra(s, n, w, cost):
    # 始点sから各頂点への最短距離
    # n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    signs = [float("inf")] * n
    used = [False] * n
    d[s] = 0

    while True:
        v = -1
        # まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
            break
        used[v] = True

        print(v)

        for j in range(n):
            if d[j] > d[v] + cost[v][j]:
                d[j] = d[v] + cost[v][j]
                signs[j] = v+1
    return d, signs


N, M = MII_split()
cost = [[float('inf') for _ in range(N)] for _ in range(N)]
for _ in range(M):
    x, y = MII_split()
    # if x > y:
    #     x, y = y, x
    cost[x - 1][y - 1] = 1
    cost[y - 1][x - 1] = 1

d, signs = dijkstra(0, N, M, cost)

# print(d, signs)

if float('inf') in signs[1:]:
    print('No')
else:
    print('Yes')
    print_list_in_2D(signs[1:])

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, bellman_ford
from scipy.sparse import csr_matrix

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

A = np.array(A)
B = np.array(B)
row = (A - 1).astype(int)
col = (B - 1).astype(int)
data = np.ones(M).astype(int)
m = csr_matrix((data, (row, col)), shape=(N, N))
d, sp = shortest_path(m, indices=0, return_predecessors=True, directed=False, method="BF")
if np.inf in d:
    print("No")
else:
    print("Yes")
    result = sp[1:] + 1
    for i in result:
        print(int(i))

Submission status: Wrong Answer

Solution code:

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

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

mi = [n] * n
mi[0] = 0
check = [n] * n

for i in range(len(route)):
    for j in range(len(route[i])):

        if route[i][j] == 1:
            if mi[j] > mi[i] + 1:
                mi[j] = mi[i] + 1
                check[j] = i

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 17 20:56:20 2020

@author: Kanaru Sato
"""
import collections

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

distance = [-1,0]
for i in range(n-1):
    distance.append(-1)

ans = [-1 for i in range(n+1)]
ans[1] = 1

q = [1]
q = collections.deque(q)

while q:
    cp = q.popleft()
    for np in connected[cp]:
        if ans[np] == -1 or distance[ans[np]] > distance[cp]:
            print(np,cp)
            q.append(np)
            ans[np] = cp
            distance[np] = distance[cp] + 1

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

Submission status: Wrong Answer

Solution code:
N,M=map(int, input().split())
visit=[0]*(N)
to_1=[0]*N
for _ in range(M):
    lis=list(map(int, input().split()))
    visit[lis[0]-1]+=1
    visit[lis[1]-1]+=1
    if lis[0] == 1 or lis[1]==1:
        to_1[lis[0]-1]=1
        to_1[lis[1]-1]=1
if visit.count(0) == 0:
    print('Yes')
    for i in range(N-1):
        if to_1[i+1] ==1:
            print(1)
        else:
            print(visit[i+1])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
n,m=list(map(int, input().split()))
a=[]
b=[]
answer=[0]*n
answer[0]=1
for i in range(m):
    c=list(map(int, input().split()))
    a.append(c[0])
    b.append(c[1])
count=1#最初から1の部屋はOKにしとく
queue=[1]
newqueue=[]
while(count<n and len(queue)!=0):
    for k in range(m):
        for j in queue:
            if(a[k]==j):
                answer[b[k]-1]=j
                count+=1
                newqueue.append(b[k])
            elif(b[k]==j+1):
                answer[a[k]-1]=j
                count+=1
                newqueue.append(a[k])
    queue=newqueue
    newqueue=[]
if(count<n):
    print('No')
else:
    print('Yes')
    for l in range(n-1):
        print(answer[l+1])

Submission status: Wrong Answer

Solution code:
n,m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(m)]
res=[0]*(n+1)

for i in range(m):
    if ab[i][0]==1:
        res[ab[i][1]]=1
    elif ab[i][1] ==1:
        res[ab[i][0]]=1
while min(res[1:]) ==0:
    for j in range(m):
        if res[ab[j][0]] !=0:
            if res[ab[j][1]] ==0:
                res[ab[j][1]] =ab[j][0]
        elif res[ab[j][1]] != 0:
            if res[ab[j][0]] ==0:
                res[ab[j][0]] =ab[j][1]
print("Yes")
for k in range(2,n+1):
    print(res[k])

Submission status: Wrong Answer

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

N, M = map(int, readline().split())
ans = []
graph = [[] for _ in range(N+1)]

for _ in range(M):
    a, b = map(int, readline().split())
    graph[a].append(b)
    graph[b].append(a)

root = 1
q = [root]
checked = [0] * (N + 1)
order = []

while q:
    x = q.pop(0)
    if checked[x]:
        continue
    checked[x] = 1
    for y in graph[x]:
        if checked[y]:
            continue
        ans.append(x)
        order.append(y-2)
        checked[y] = 1
        q.append(y)

if len(order) != N - 1:
    print('No')
else:
    print('Yes')
    for i in range(len(order)):
        j = order.index(i)
        print(ans[j])

Submission status: Wrong Answer

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n,m=LI()
  ans=[-1]*n

  q=collections.deque()
  v=[[] for _ in range(n)]
  for _ in range(m):
    a,b=LI()
    a-=1
    b-=1
    v[a].append(b)
    v[b].append(a)
    if a==0:
      q.append((0,b,0))
    elif b==0:
      q.append((0,a,0))

  print(q)

  while q:
    moto,nxt,stp=q.popleft()
    if ans[nxt]==-1:
      ans[nxt]=moto
    else:
      continue

    for x in v[nxt]:
      if ans[x]==-1:
        q.append((nxt,x,stp+1))

  if -1 in ans[1:]:
    print('No')
    exit()

  print('Yes')
  for x in ans[1:]:
    print(x+1)

main()
# print(main())

Submission status: Wrong Answer

Solution code:
def dijkstra(s,n,w,cost):
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0

    while True:
        v = -1
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True

        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d


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

cost = [[float("inf") for i in range(N)] for i in range(N)]
for i in range(M):
    A, B = map(int, input().split())
    A -= 1
    B -= 1
    cost[A][B] = 1
    cost[B][A] = 1

distance = dijkstra(0, N, M, cost)

for d in distance:
    if d == float("inf"):
        print("No")
        exit()

print("Yes")
for i in range(1, N):
    print(distance[i])

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ans = {i:0 for i in range(1,N+1)}
ans[1] = 10000000
route = {i:[] for i in range(1,N+1)}
for _ in range(M):
    a,b = map(int,input().split())
    route[a].append(b)
    route[b].append(a)
x = [1]
for _ in range(M):
    for i in x:
        tmp = []
        for j in route[i]:
            #print(j)
            if ans[j] == 0:
                ans[j] = i
            tmp.append(j)
    x = tmp
    #print(ans,x)
print('Yes')
for i in ans.keys():
    if i != 1:
        print(ans[i])

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
li=[[] for i in range(n)]
for i in range(m):
    ai,bi=map(int,input().split())
print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

num = [0 for _ in range(N)]
num[0] = 1

dist = [10**15 for _ in range(N)]
dist[0] = 0

queue = deque([1])
visited = [False for _ in range(N)]

while queue:
    v = queue.pop()
    if(visited[v-1]):
        continue
    visited[v-1] = True
    for value in graph[v]:
        if(visited[value-1]):
            continue
        if(dist[value-1] > dist[v-1]+1):
            dist[value-1] = dist[v-1]+1
            num[value-1] = v
        queue.append(value)


if(0 not in num):
    print("Yes")
    for i in range(1, len(num)):
        print(num[i])
else:
    print("No")

Submission status: Wrong Answer

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

import heapq

def dijkstra(edges,num_v,start):
      dist = [float("inf")] * num_v
      dist[start] = 0
      q = []
      heapq.heappush(q,[0,start])#[0,0]とは1番目に頂点のインデックス、0番目に頂点までのコストを格納する
    
      while len(q) >0:
        #ヒープから取り出し
        _,u = heapq.heappop(q)
        for i in edges[u]:
            if dist[i] > dist[u] + 1:
                #頂点までのコストが更新できれば更新してヒープに登録
                dist[i] = dist[u] + 1
                heapq.heappush(q,[dist[u] + 1,i])
      return dist
result = dijkstra(m_load,n,0)
if float("inf") in result:
  print("No")
else:
  print("Yes")
  for i in range(1,n):
    print(result[i])

Submission status: Wrong Answer

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

path = []

for _ in range(m):
    ai, bi = map(int, input().split())
    path.append([ai, bi])

# print(path)

linked = set()
linked.add(1)
ans = {}

for _ in range(m):
    for pi in path:
        if pi[0] in linked:
            linked.add(pi[1])
            if pi[1] not in ans:
                ans[pi[1]] = pi[0]

        elif pi[1] in linked:
            linked.add(pi[0])
            if pi[0] not in ans:
                ans[pi[0]] = pi[1]

# print(linked)
# print(ans)
if len(linked) == n:
    print('Yes')
    for i in range(1, n):
        print(ans[i+1])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
N , M = map(int , input().split())
A = [ 0 for i in range(M)]
B = [ 0 for i in range(M)]
for i in range(M):
  A[i] , B[i] = map(int , input().split())

direction = [N for i in range(N)]
point = [N for i in range(N)]
for i in range(M):
  if A[i] == 1:
    direction[B[i] - 1] = 1
    point[B[i] - 1] = 1
  if B[i] == 1:
    direction[A[i] - 1] = 1
    point[A[i] - 1] = 1
step = 1
k=1
while k != 0:
  k = 0

  for i in range(M):
    a = point[A[i] - 1]
    b = point[B[i] - 1]
    m = min([a, b])
    if m == step and a != b:
      if a == m:
        direction[B[i] - 1] = A[i]
      if b == m:
        direction[A[i] - 1] = B[i]
      k += 1

  step += 1
print('Yes')
for i in range(N - 1):
  print(str(direction[i + 1]))

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
node = [[0 for _ in range(n)] for _ in range(n)]
ans=[0 for _ in range(n)]
L=[]
for _ in range(m):
    a,b = map(int,input().split())
    node[a-1][b-1] = 1
    node[b-1][a-1] = 1
for i in range(n):
    if node[i][0] == 1:
        ans[i] = 1
        node[i][0] = 0
        node[0][i] = 0
        L.append(i)
while L:
    for i in L:
        tmp=[]
        for j in range(n):
            if node[j][i] == 1 and ans[j]==0:
                ans[j] = i + 1
                node[j][i] = 0
                node[i][j] = 0
                tmp.append(j)
    L=tmp
if ans.count(0)!=1:
    print('No')
else:
    for i in range(n):
        if i==0:
            print('Yes')
        else:
            print(ans[i])

Submission status: Wrong Answer

Solution code:
import heapq
import sys

input = sys.stdin.readline

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

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

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

# 頂点iまでの最短距離
dist = Dijkstra_heap(0, edge)
if 10**6 in dist:
  print("No")
  exit()
for i in dist[1:]:
  print(i)

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
root=[[] for _ in range(n)]
for i in range(m):
	a,b=map(int,input().split())
	root[a-1].append(b-1)
	root[b-1].append(a-1)
times=[0]*n
sign=[-1]*n
sign[0]=0
que=deque([0])
while que:
	q=que.pop()
	for i in root[q]:
		if sign[i]==-1:
			sign[i]=q
			que.extend(root[i])
for i in range(n-1):
	print(sign[i+1]+1)

Submission status: Wrong Answer

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

sys.setrecursionlimit(100000000)

def yn(b):
    print("Yes" if b==1 else "No")
    return

def xxx(t,memo,ans):
    for a in memo[t]:
        if ans[a] == -1 or ans[a] > t:
            ans[a]=t
            xxx(a,memo,ans)


def resolve():
    readline=sys.stdin.readline

    n,m=map(int, readline().rstrip().split())
    memo=[[] for i in range(n)]
    ans=[-1]*n
    ans[0]=0
    for i in range(m):
        a,b=map(int, readline().rstrip().split())
        memo[a-1].append(b-1)
        memo[b-1].append(a-1)
    xxx(0,memo,ans)
    #tt=[0]
    #nx=[]
    #for t in tt:
    #    for a in memo[t]:
    #        if ans[a]
        
    #memo

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


    #arr=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Wrong Answer

Solution code:
N, M = [int(i) for i in input().split()]
from collections import deque

graph = [deque([]) for _ in range(N + 1)]
for _ in range(M):
    u, v = [int(x) for x in input().split()]
    graph[u].append(v)
    graph[v].append(u)  # 無向グラフ


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


def bfs(root):
    if root is None:
        return
    q = deque()
    q.append(root)
    while q:
        r = q.pop()
        for n in graph[r]:
            if sirube[n] == -1:
                sirube[n] = r
                q.append(n)

bfs(1)  # スタート

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

Submission status: Wrong Answer

Solution code:
# from collections import defaultdict
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

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

# d = defaultdict(list)
graph = [[0 for _ in range(n)] for _ in range(n)]
for ai, bi in zip(a, b):
    graph[ai - 1][bi - 1], graph[bi - 1][ai - 1] = 1, 1
graph = np.array(graph)
# print(graph)
shortest = shortest_path(graph)
# print(shortest)
is_ok = True
for i in range(1, n):
    # print(shortest[i][0])
    if shortest[i][0] < 1:
        is_ok = False
        break
print('Yes' if is_ok else 'No')
for i in range(1, n):
    print(int(shortest[i][0]))

Submission status: Wrong Answer

Solution code:
n,m,*ab=map(int,open(0).read().split())
path={}
for i in range(n):
  path[i]=[]
for i in range(m):
  a,b=ab[i*2]-1,ab[i*2+1]-1
  path[a].append(b)
  path[b].append(a)
direction=[i for i in range(n)]
fin=[False for i in range(n)]
fin[0]=True
i=0
queue=[0]
while i<n:
  i+=1
  queue2=queue.copy()
  queue.clear()
  if len(queue)==0:
    break
  for j in queue2:
    fin[j]=True
    for k in path[j]:
      if not fin[k]:
        direction[k]=j
        fin[k]=True
        queue.append(k)
print('Yes')
for i in range(1,n):
  print(direction[i]+1)

Submission status: Wrong Answer

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


YES = "Yes"  # type: str


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    root = []
    for i in range(N):
        root.append([])
    next = [-1] * N
    for a, b in zip(A, B):
        root[a - 1].append(b - 1)
        root[b - 1].append(a - 1)

    for arr in root:
        if len(arr) == 0:
            print("No")
            exit()
    
    s = set()
    s.add(0)

    while len(s) != 0:
        #print(s)
        #print(next)
        n = s.pop()
        for i in root[n]:
            if next[i] == -1:
                next[i] = n
                if i != 0:
                    s.add(i)

    print("Yes")
    for i in range(1, len(next)):
        print(next[i] + 1)
    

    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path
from scipy.sparse import csr_matrix

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

A = np.array(A)
B = np.array(B)
row = (A - 1).astype(int)
col = (B - 1).astype(int)
data = np.ones(M).astype(int)
m = csr_matrix((data, (row, col)), shape=(N, N))
d, sp = shortest_path(m, indices=0, return_predecessors=True, directed=False)
if np.inf in d:
    print("No")
else:
    print("Yes")
    result = sp[1:] + 1
    for i in result:
        print(int(i))

Submission status: Wrong Answer

Solution code:
(N,M) = map(int,input().split())
ANSlist = [0]*N
routelist = []
for i in range(N):
    routelist.append([i+1])
    routelist[i].append([0])
for i in range(M):
    (A,B) = map(int,input().split())
    routelist[A-1][1].append(B)
    routelist[B-1][1].append(A)
ANS_tag = [1]
root = routelist.pop(0)
for i in range(N):
    NewANS_tag = []
    for k in ANS_tag:
        Newroutelist = []
        for j in routelist[:]:
            if k in j[1]:
                NewANS_tag.append(j[0])
                ANSlist[j[0]-1] = k
            else:
                Newroutelist.append(j)
        routelist = Newroutelist       
    ANS_tag = NewANS_tag

for i in ANSlist:
    if i == 0:
        continue
    print(i)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
li=[[] for i in range(n)]
for i in range(m):
    ai,bi=map(int,input().split())
    li[ai-1].append(bi-1)
    li[bi-1].append(ai-1)
flag=0
for i in range(n):
    if len(li[i])==0:
        flag=1
        break
if flag==1:
    print("No")
else:
    print("Yes")
    for i in range(1,n):
        print(min(li[i])+1)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
l=[[] for _ 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)

p=[0]*n
p[0]=1
x=0
cnt=1
k=10**5
while 0 in p and k>0:
    for to in l[x]:
        if p[to]==0:
            p[to]=cnt
    x=to
    cnt+=1
    k-=1
if 0 in p:
    print("No")
else:
    p[0]=0
    print("Yes")
    for i in range(1,n):
        print(p.index(p[i]-1)+1)