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:
def resolve():
    n, m = map(int, input().split()) # 標準入力1行目の処理、n頂点、m辺
    adj = [[] for i in range(n+1)] # 隣接リスト初期化、要素数は頂点数
    for i in range(m):
        A, B = map(int, input().split())
        adj[A].append(B) # このappendのやり方だと、adj[0]が空になることに注意
        adj[B].append(A) # （問題文の頂点インデックスが1始まりであるため）
    #print(adj)
    # 隣接リストさえ作成できたら、あとはBFSで全探索するだけ

    from collections import deque
    q = deque([1])
    ans = [-1 for i in range(n+1)]
    while q:
        v = q.popleft() # vertex(頂点)の意
        for u in adj[v]:
            if ans[u] == -1: # 未踏なら
                ans[u] = v
                q.append(u)
    print("yes")
    for i in range(2, n+1):
        print(ans[i])

resolve()

Submission status: Wrong Answer

Solution code:
from collections import deque
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)

#print(graph)

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

d = deque()
d.append(1)

#print(d)

while d:
    v = d.popleft()
    for i in graph[v]:
        if dist[i] != -1:
            continue
        dist[i] = dist[v] +1
        d.append(i)
print("Yes")
ans = dist[2:]
print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
from collections import deque
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)

#print(graph)

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

d = deque()
d.append(1)

#print(d)

while d:
    v = d.popleft()
    for i in graph[v]:
        if dist[i] != -1:
            continue
        dist[i] = dist[v] +1
        d.append(i)
print("YES")
ans = dist[2:]
print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m = map(int, input().split())
print("YES")

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)

#print(graph)

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

d = deque()
d.append(1)

#print(d)

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[2:]
print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
from collections import deque
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)

#print(graph)

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

d = deque()
d.append(1)

#print(d)

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:]
print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
from collections import deque

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

n,m = mapinput()
rootlist = [[] for i in range(n)]
flag = [False for i in range(n)]

for i in range(m):
    a,b= mapinput()
    rootlist[a-1].append(b)
    rootlist[b-1].append(a)

que = deque()
que.append(1)
while len(que) !=0:
    now = que.popleft()
    for room in rootlist[now-1]:
        if flag[room-1] == False:
            flag[room-1] = now
            que.append(room)

print('Yes')
for i in range(1,n):#スライスで実装
    rootlist[i]

Submission status: Wrong Answer

Solution code:
from collections import deque

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

n,m = mapinput()
rootlist = [[] for i in range(n)]
flag = [False for i in range(n)]

for i in range(m):
    a,b= mapinput()
    rootlist[a-1].append(b)
    rootlist[b-1].append(a)

que = deque()
que.append(1)
while len(que) !=0:
    now = que.pop()
    for room in rootlist[now-1]:
        if flag[room-1] == False:
            flag[room-1] = now
            que.append(room)

print('Yes')
for i,root in enumerate(flag):#スライスで実装
    if i == 0:
        continue
    print(root)

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import heapq
import queue
import itertools
import functools
import operator
import time

readline = sys.stdin.readline
 
IPS = lambda: readline().rstrip()
IP = lambda: int(readline().rstrip())
MP = lambda: map(int, readline().split())
LS = lambda: list(map(int, readline().split()))

def solve():
    for _ in range(1):
        n,m = MP()
        adj = [[] for i in range(n+1)] 
        
        for i in range(m):
            a,b = MP()
            adj[a].append(b)
            adj[b].append(a)
            
        q = queue.Queue()
        vis = [0]*(n+1)
        level = [0]*(n+1)
        q.put(1)
        vis[1]=1
        level[1] = 0
        
        while q.qsize():
            p = q.get()
            for elem in adj[p]:
                if not vis[elem]:
                    level[elem] = level[p]+1
                    vis[elem]=1
                    q.put(elem)
                    
        fg = 0
        for i in range(2,n+1):
            if level[i]==0: 
                fg=1
                break
            
        if fg: print("No")
        else:
            print("Yes")
            for i in range(2,n+1):
                print(level[i])
       
       
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M = [int(i) for i in input().split(' ')]
    
links = [[] for _ in range(N + 1)]

for _ in range(M):
    a, b = [int(i) for i in input().split(' ')]
    links[a].append(b)
    links[b].append(a)

q = deque([1])

results = [-1 for _ in range(N + 1)]

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

print('YES')
print('\n'.join([str(i) for i in results[2:]]))

Submission status: Wrong Answer

Solution code:
#inport
import sys
import numpy as np
from collections import deque


#input
N,M = [int(x) for x in sys.stdin.readline().split()]
g = [[] for _ in range(N+1)]

for _ in range(M):
    a, b = [int(x) for x in sys.stdin.readline().split()]
    g[a].append(b)
    g[b].append(a)



quetmp = deque([1])
d = [None] * (N+1)
d[1] = 0
num_crew = 1
while quetmp:
    v = quetmp.popleft()
    for i in g[v]:
        print(i)
        print(d[i])
        if d[i] is None:
            d[i] = v
            quetmp.append(i)
            num_crew = num_crew + 1

if num_crew == N:
    print('Yes')
    for i in range(N-1):
        print(d[i+2])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
import glob
import math


# 問題ごとのディレクトリのトップからの相対パス
REL_PATH = 'ABC\\168\\D'

# テスト用ファイル置き場のトップ
TOP_PATH = 'C:\\AtCoder'

class Common:

    problem = []
    index = 0

    def __init__(self, rel_path):
        self.rel_path = rel_path

    def initialize(self, path):
        file = open(path)
        self.problem = file.readlines()
        self.index = 0
        return

    def input_data(self):
        try:
            IS_TEST
            self.index += 1
            return self.problem[self.index-1]

        except NameError:
            return input()

    def resolve(self):
        pass

    def exec_resolve(self):
        try:
            IS_TEST
            for path in glob.glob(TOP_PATH + '\\' + self.rel_path + '/*.txt'):
                print("Test: " + path)
                self.initialize(path)
                self.resolve()
                print("\n\n")
        except NameError:
            self.resolve()


class Solver(Common):

    alph = []

    def rec(self, result, now, max, N):

        if now == N:
            res = ""
            for i in result:
                res += self.alph[i]
            print(res)
            return

        if now == 0:
            result[0] = 0
            self.rec(result, now+1, 0, N)
            return

        for i in range(0, max+2):
            if i == N:
                return
            result[now] = i
            if i > max:
                self.rec(result, now+1, i, N)
            else:
                self.rec(result, now+1, max, N)

    def resolve(self):

        count = 0

        N, M = map(int, self.input_data().split())
        node = [list(map(int, self.input_data().split())) for i in range(M)]
        sp = [[0, 200000] for i in range(N+1)]   # signpost
        path = [[] for i in range(N+1)]
        for n in node:
            path[n[0]].append(n[1])
            path[n[1]].append(n[0])

        next = [1]
        sp[1][1] = 0
        while len(next) != 0:
            now = next.pop(0)
            for n in path[now]:
                if sp[n][1] > sp[now][1]+1:
                    sp[n][0] = now
                    sp[n][1] = sp[now][1]+1
                    next.append(n)


        print('yes')
        for i in range(2,N+1):
            print(str(sp[i][0]))

solver = Solver(REL_PATH)
solver.exec_resolve()

Submission status: Wrong Answer

Solution code:
from collections import deque
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)

#print(graph)

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

d = deque()
d.append(1)

while d: #dの中が空になるまで続ける
  v = d.popleft()#一番最初に入れたものから探索する。
  for i in graph[v]:#vから行けるところを探索。例v=1,i=2, v=2,i=1,3,4
    if dist[i] != -1: #iが未訪問でなければ（=訪問済みであれば）
      continue#何もしない
    dist[i] = dist[v] + 1#iのdistにv＋1したものを追加
    d.append(i)#訪問リストにiを追加

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

Submission status: Wrong Answer

Solution code:
#inport
import sys
import numpy as np

#input
N,M = map(int, sys.stdin.readline().split())
P = [list(map(int, sys.stdin.readline().split())) for i in range(M)]

#shori
##初期化
P = np.array(P)     
ans = np.zeros((N,2))
tmp_latest = np.zeros(1)
tmp_latest_tmp = np.zeros(1)
tmp_latest[0] = 1
pos_latest = 0
num_latest = 1
ans[0][1] = 1 #部屋1をてがかりありに
flg_pos = 1
flg_fale = 0
num_crew = 1
num_left_room = N-1
left_room = np.zeros(N)

for i in range(N):
    ans[i][0] = i + 1

while num_crew < N:
    if flg_pos == 0:
        flg_fale = 1
        break

    flg_pos = 0
    for i in range(num_latest):
        tmp_room_num = tmp_latest[i]
        tmp_root = P[np.any( P == int(tmp_room_num), axis = 1)]
        root_loop_n = int(np.size(tmp_root)/2)
        print(tmp_root)
        print(tmp_latest)
        for j in range(root_loop_n):
            if tmp_root[j][0]==tmp_latest[i]:
                if(ans[tmp_root[j][1]-1][1]==0):
                    tmp_latest_tmp = np.insert(tmp_latest_tmp, 0, tmp_root[j][1])
                    ans[tmp_root[j][1]-1][1] = tmp_latest[i]
                    print(tmp_latest[i])
                    num_crew = num_crew + 1
                    flg_pos = 1
            elif tmp_root[j][1]==tmp_latest[i]:
                if(ans[tmp_root[j][0]-1][1]==0):
                    tmp_latest_tmp = np.insert(tmp_latest_tmp, 0, tmp_root[j][0])
                    ans[tmp_root[j][0]-1][1] = tmp_latest[i]
                    print(tmp_latest[i])
                    num_crew = num_crew + 1
                    flg_pos = 1               
        P = np.delete(P, np.where(P == int(tmp_room_num))[0], axis = 0)

    #Nループ終了時にtmp_latestを更新
    tmp_latest = np.insert(tmp_latest, num_latest, tmp_latest_tmp)
    for j in range(num_latest):
        tmp_latest = np.delete(tmp_latest,0)
    num_latest = np.size(tmp_latest)
    tmp_latest_tmp = np.zeros(1)

    
if flg_fale == 0:
    print('Yes')
    for i in range(N-1):
        print(int(ans[i+1][1]))
else:
    print('No')

Submission status: Wrong Answer

Solution code:
n,m=[int(i) for i in input().split()]
from collections import defaultdict
graph=defaultdict(list)
for i in range(m):
    p,c=[int(i) for i in input().split()]
    graph[p].append(c)
    graph[c].append(p)


ans=[float("inf")]*(n+1)
dir_=[0]*(n+1)
visited=[0]*(n+1)
ans[1]=0
def bfs(c):
    queue=[]
    queue.append(c)
    while queue:
        #print(queue)
        start=queue.pop(0)
        
        
        for i in graph[start]:
            if not visited[i]:
                visited[i]=1
                dir_[i]=start
                queue.append(i)
        
bfs(1)

print(dir_)
if 0 in dir_[2:]:
    print("No")
else:
    print("Yes")
    for j in dir_[2:]:
        print(j)

Submission status: Wrong Answer

Solution code:
import heapq
import numpy as np

N, M = [int(x) for x in input().split(" ")]

e = {i: [] for i in range(N)}
for _ in range(M):
  a, b = [int(x)-1 for x in input().split(" ")]
  e[a] = e[a] + [b]
  e[b] = e[b] + [a]

# roots = [[int(x) for x in input().split(" ")] for _ in range(M)]

d = np.ones(N, dtype=int) * np.inf
d[0] = 0
prev = np.ones(N, dtype=int) * -1
q = [(d[0], 0)]
heapq.heapify(q)

while len(q) != 0:
  c, u = heapq.heappop(q)
  for nv in e[u]:
    alt = d[u] + 1
    if d[nv] > alt:
      d[nv] = alt
      prev[nv] = u
      heapq.heappush(q, (alt, nv))

print("YES")
for p in prev[1:]:
  print(p+1)

Submission status: Wrong Answer

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

d = [0 for i in range(n)]
d[0] = -1
used = []
k = 0

while True:
    for i in range(n):
        if (d[i] != 0) & (((i + 1) in used) == False):
            k = i + 1
            break
    if k in used:
        break
    l = []
    for j in range(len(ab)):
        if ab[j][0] == k:
            if d[ab[j][1] - 1] == 0:
                d[ab[j][1] - 1] = k
            l.append(ab[j])
        elif ab[j][1] == k:
            if d[ab[j][0] - 1] == 0:
                d[ab[j][0] - 1] = k
            l.append(ab[j])
    for j in range(len(l)):
        ab.remove(l[j])
    used.append(k)

if 0 in d:
    print('No')
else:
    print('Yes')
    for i in range(1, n):
        print(d[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

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

g = [[] for _ in range(n)]  # 隣接リスト

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


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)
if len(d) != 0:
  print("Yes")
  for i in d[1:]:
    print(i)
else:
  print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque
from copy import copy
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
connection ={i:[] for i in range(0,N+1)}
connection[0] =[1]
#connection[1] =[0]
#構造入力
for i in range(M):
    a,b = (int(x) for x in input().split())
    connection[a].append(b)
    connection[b].append(a)

# 幅優先探索
parent ={i:-1 for i in range(1,N+1)} #親＝通過済、通過してない部屋はー１
parent[1] =0
children = deque()
children.extend(connection[1])
for i in children:
    parent[i] =1
while children:
    next =children.popleft()

    for i in connection[next]:
        if parent[i] != -1:
            continue
        else:
            parent[i] =next
            next_next =connection[i].copy()
            next_next.remove(parent[i])
            children.extend(next_next)
            next_next.clear()
#出力
print("Yes")
for i in range(2,N+1):
    print(parent[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
from copy import copy
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
connection ={i:[] for i in range(0,N+1)}
connection[0] =[1]
#connection[1] =[0]
#構造入力
for i in range(M):
    a,b = (int(x) for x in input().split())
    connection[a].append(b)
    connection[b].append(a)

# 幅優先探索
parent ={i:-1 for i in range(1,N+1)} #親＝通過済、通過してない部屋はー１
parent[1] =0
children = deque()
children.extend(connection[1])
for i in children:
    parent[i] =1
while children:
    next =children.popleft()

    for i in connection[next]:
        if parent[i] != -1:
            continue
        else:
            parent[i] =next
            next_next =connection[i].copy()
            next_next.remove(parent[i])
            children.extend(next_next)
            next_next.clear()
#出力
for i in range(2,N+1):
    print(parent[i])

Submission status: Wrong Answer

Solution code:
# 入力の処理
N, M = map(int, input().split())
A = []
B = []
Room = []
Guide = []
for i in range(N):
    Room = Room + [i+1]
    Guide = Guide + [0]
for i in range(M):
    Ai, Bi = map(int, input().split())
    A = A + [Ai]
    B = B + [Bi]

# 道しるべの付与されていない部屋を順番に検討する
# 通路にj番の部屋に通じているものがあれば、その通路が通じている部屋に「j」の道しるべを配置する
check = [1]
while len(check) > 0:
    j = check[0]
    dellist = []
    for i in range(len(A)):
        if A[i] == j:
            dellist = dellist + [i]
            if Guide[B[i] - 1] == 0:
                Guide[B[i] - 1] = j
                check = list(set(check + [B[i]]))
        elif B[i] == j:
            dellist = dellist + [i]
            if Guide[A[i] - 1] == 0:
                Guide[A[i] - 1] = j
                check = list(set(check + [A[i]]))

    for i in range(len(dellist)):
        del A[dellist[i] - i]
        del B[dellist[i] - i]

    Room.remove(j)
    check.remove(j)

# whileを抜けたら、Guide[0]以外にはすべてに何か知らの0でない番号が入っているはず。
# 0が残っていなかったら、no

del Guide[0]

if Guide.count(0) == 0:
    print('Yes')
    for i in range(len(Guide)):
        print(Guide[i])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
n, m = list(map(int, input().split()))
paths = []
for i in range(m):
	paths.append(list(map(int, input().split())))
roots=[set() for i in range(n)]
for ab in paths:
    a, b = ab
    roots[a-1].add(b-1)
    roots[b-1].add(a-1)
passed = roots[0] | {0}
next_root = roots[0]
cnts = [0 for i in range(n)]
cnt = 1
while next_root !=set():
    r = set()
    for i in next_root :
        r |= roots[i]
        cnts[i] = cnt
    next_root = r - passed
    passed |= r
    cnt += 1
del cnts[0]
if 0 in cnts:
    print('No')
else:
	print('Yes')
	for n in cnts:
		print(n)

Submission status: Wrong Answer

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

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

queue = [0]
dist = [0] * N
prev = [-1] * N
while(len(queue) != 0):
    now = queue[0]
    queue.pop(0)
    for i in loads[now]:
        if dist[i] != 0:
            continue
        else:
            queue.append(i)
            dist[i] = dist[now] + 1
            prev[i] = now + 1

for i in prev[1:]:
    print(i)

Submission status: Wrong Answer

Solution code:
from collections import deque

WHITE=0
GRAY=1
BLACK=2

nList = []
labelList = []
color = []
Q = deque([])

def readinput():
    global nList
    global color
    global Q
    global labelList

    n,m=list(map(int,input().split()))
    nList = []
    for _ in range(n+1):
        nList.append([])  # 1-オリジンの隣接リスト

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

    labelList = [0]*(n+1)
    color = [WHITE]*(n+1)
    Q = deque([])

    print(nList)

def bfs(p):
    global Q
    global nList
    global color
    global labelList

    Q.append(p)
    color[p]=GRAY
    #print(Q)
    #print(color)
    while(len(Q)>0):
        current=Q.popleft()
        for next in nList[current]:
            if(color[next]==WHITE):
                Q.append(next)
                color[next]=GRAY
                labelList[next]=current
                #print(Q)
                #print(color)
                #print(labelList)
        color[current]=BLACK

def main():

    bfs(1)


if __name__=='__main__':
    readinput()

    main()
    print('Yes')
    for l in labelList[2:]:
        print(l)

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(G, ans):
  q = deque([1])

  seen = [False for _ in range(N+1)]
  while q:
    node = q.popleft()
    seen[node] = True

    for i in G[node]:
      if i in q:
        continue
      if seen[i] == True:
        continue
      q.append(i)
      ans[i] = node

  return ans

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

G = [[] for _ in range(N+1)]

ans = [0 for i in range(N + 1)]

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

print(G[1])
bfs(G, ans)

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
BIG = 10**5 + 1
def aaa(i,rooms,routes):

    while BIG in rooms:
        for route in routes:
            l = route[0] - 1
            r = route[1] - 1
            if l == i:
               # print(i,l+1,r+1,rooms,routes)
                if rooms[l] < rooms[r] and rooms[l] < BIG:
                    rooms[r] = rooms[l] + 1
                    i = r
                elif rooms[l] > rooms[r] and rooms[r] < BIG:
                    rooms[l] = rooms[r] + 1
                    i = l
    return rooms

def double_dots(n,m,ab):
    ab_sorted = sorted(ab)
    #print(ab_sorted)
    rooms = [BIG] * n
    rooms[0] = 0
    i = 0
    ddd = aaa(i,rooms,ab_sorted)
    if len(ddd) > 1:
        print("Yes")
        for s in ddd[1:]:
            print(s)
    else:
        print("No")            
if __name__ == "__main__":
    n,m = map(int,input().split())
    ab = [list(map(int,input().split())) for _ in range(m)]

    #print(ab)
    double_dots(n,m,ab)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
BIG = 10**5 + 1
def aaa(i,rooms,routes):

    while BIG in rooms:
        for route in routes:
            l = route[0] - 1
            r = route[1] - 1
            if l == i:
                print(i,l+1,r+1,rooms,routes)
                if rooms[l] < rooms[r] and rooms[l] < BIG:
                    rooms[r] = rooms[l] + 1
                    i = r
                elif rooms[l] > rooms[r] and rooms[r] < BIG:
                    rooms[l] = rooms[r] + 1
                    i = l
    return rooms

def double_dots(n,m,ab):
    ab_sorted = sorted(ab)
    print(ab_sorted)
    rooms = [BIG] * n
    rooms[0] = 0
    i = 0
    ddd = aaa(i,rooms,ab_sorted)
    if len(ddd) > 1:
        print("Yes")
        for s in ddd[1:]:
            print(s)
    else:
        print("No")            
if __name__ == "__main__":
    n,m = map(int,input().split())
    ab = [list(map(int,input().split())) for _ in range(m)]

    print(ab)
    double_dots(n,m,ab)

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
graph=[[] for i in range(n)]
sirusi=[0]*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 i in graph[v]:
        if visited[i]:continue
        visited[i]=True
        sirusi[i]=v
        D.append(i)
print("Yes")
print(sirusi)
for i in range(1,n):
    print(sirusi[i]+1)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
a=[list(map(int,input().split())) for i in range(m)]
ikeruheya = [[] for i in range(n)]
ans = [0]*(n+1)
check = [0]*n

for i in range(m):
    ikeruheya[a[i][0]-1].append(a[i][1])
    ikeruheya[a[i][1]-1].append(a[i][0])
    
next=[1]
count = 1
while len(next) != 0 and count < n:
    imaheya = next.pop(0)
    for j in range(len(ikeruheya[imaheya-1])):
        if check[ikeruheya[imaheya-1][j]-1]==0:
            ans[ikeruheya[imaheya-1][j]]= imaheya 
            check[ikeruheya[imaheya-1][j]-1] = 1
            next.append(ikeruheya[imaheya-1][j])
            count += 1
            
print("Yes")
for i in range(2, n+1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
#atcoder template
def main():
    import sys
    imput = sys.stdin.readline
    #文字列入力の時は上記はerrorとなる。
    #ここにコード
    #input
    N, M = map(int, input().split())
    AB = [map(int, input().split()) for _ in range(M)]

    C = [[] for _ in range(N+1)]
    for a, b in AB:
        C[a].append(b)
        C[b].append(a)     

    #output
    #queue
    from collections import deque

    #iを出発して、ループが形成できるか確認。
    search_stack = deque([1])

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

    while search_stack:
        next_position = search_stack.popleft()
        for node in C[next_position]:
            if signpost[node] == -1:
                signpost[node] = next_position
                search_stack.append(node)

    print("Yes")
    for i in range(2, N):
        print(signpost[i])

    #N = 1のときなどcorner caseを確認！
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
NM = [int(e) for e in input().split()]
N = NM[0]
M = NM[1]

routes = []
mark = [None for e in range(N)]
mark[0] = 0
append = routes.append

for i in range(M):
	route = [int(e) for e in input().split()]
	if route[0] == 1:
		mark[route[1] - 1] = 1
		continue
	if route[1] == 1:
		mark[route[0] - 1] = 1
		continue
	append(route)

routes_ = routes.copy()  

while None in mark:
 
	routes = routes_.copy()
  
	for route in routes:
		l = route[0]
		r = route[1]

		if mark[l - 1] == None and mark[r - 1] != None:
			mark[l - 1] = r
			routes_.remove(route)
		elif mark[l - 1] != None and mark[r - 1] == None:
			mark[r - 1] = l
			routes_.remove(route)
  
print('yes')

for i in range(N):
  if i == 0:
    continue
  print(mark[i])

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time

sys.setrecursionlimit(10 ** 7)

from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

adj = [[] for _ in range(n)]

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


import heapq

MAX = 10 ** 9 + 5

visited = [False for _ in range(n)]
dist = [MAX for _ in range(n)]

def dji(start):
    dist[start] = 0
    q = [(0, 0)]
    while len(q) > 0:
        v = heapq.heappop(q)
        if visited[v[1]]:
            continue
        visited[v[1]] = True
        for u in adj[v[1]]:
            if dist[v[1]] + 1 < dist[u]:
                dist[u] = dist[v[1]] + 1
                heapq.heappush(q, (dist[u], u))

dji(0)
if all(visited):
    print("Yes")
    for i in dist[1:]:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
Z = input().split()
N = int(Z[0])
M = int(Z[1])
A = []
L = []
answer = ''
for i in range(M):
  L.append([int(l) for l in input().split()])
S = [1]
while len(A) < N-1:
  lenA = len(A)
  for s in S:
    for l in L:
      if s in l:
        s_inv = [i for i in l if i != s][0]
        if s_inv not in [a[0] for a in A]:
          A.append([s_inv, s])
          S.append(s_inv)
        L.remove(l)
    S.remove(s)
  if len(A) == lenA:
    answer = 'No'
    print(answer)
    break
if answer == '':
  answer = 'Yes'
  print(answer)
  A.sort()
  for a in A:
    print(a[1])

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time

sys.setrecursionlimit(10 ** 7)

from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

adj = [[] for _ in range(n)]

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


import heapq

MAX = 10 ** 9 + 5

visited = [False for _ in range(n)]
dist = [MAX for _ in range(n)]

def dji(start):
    dist[start] = 0
    q = [(0, 0)]
    while len(q) > 0:
        v = heapq.heappop(q)
        if visited[v[1]]:
            continue
        visited[v[1]] = True
        for u in adj[v[1]]:
            if dist[v[1]] + 1 < dist[u]:
                dist[u] = dist[v[1]] + 1
                heapq.heappush(q, (dist[u], u))

dji(0)
print(dist)
if all(visited):
    print("Yes")
    for i in dist[1:]:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
#ABC168D
def main():
    import sys
    from collections import defaultdict
    from collections import deque
    N, M = map(int, sys.stdin.readline().split())
    AB = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
    #print(AB)
    
    edge = defaultdict(list)
    for ab in AB:
        edge[ab[0]-1] +=[ab[1]-1]
        edge[ab[1]-1] +=[ab[0]-1]
    
    #print(edge)
    flag = [-1 for i in range(N)]
    def bfs(start, queue=deque([])):
        queue += [start]
        flag[start] =1
        while queue:
            now = queue.popleft()
            for ch in edge[now]:
                if flag[ch]==-1:
                    flag[ch] = now+1
                    queue.append(ch)
            
            
    
    bfs(0)
    for f in flag[1:]:
        print(f)
        
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
ans=[0]*(n+1)
adj=[[] for _ in range(n+1)]
for i in range(m):
    u,v=map(int,input().split())
    adj[u].append(v)
    adj[v].append(u)
que=deque([1])
vis=[0 for _ in range(n+1)]
vis[1]=1
while que:
    t=que.popleft()
    #print(t)
    for i in adj[t]:
        #print(i)
        if vis[i]==1:
            continue
        vis[i]=1
        ans[i]=t
        que.append(i)

if 0 in ans[2:]:
    print("NO")
else:
    print("YES")
    for i in ans[2:]:
        print(i)