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: Runtime Error

Solution code:
S = input()
N = int(S[0])
M = int(S[2])
P = []
for i in range(M):
    P.append(input().split())
Q = [0]*(N+1)
Q[0] = 1
Q[1] = 1
fin = [1]
done = []
T = True
while 0 in Q:
    for i in fin:
        if i not in done:
            for j in range(M):
                x0 = int(P[j][0])
                x1 = int(P[j][1])
                if x0 == i and Q[x1] == 0:
                    Q[x1] = i
                    if x1 not in fin:
                        fin.append(x1)
                    P[j][0] = 0
                    P[j][1] = 0
                if x1 == i and Q[x0] == 0:
                    Q[x0] = i
                    if x0 not in fin:
                        fin.append(x0)
                    P[j][0] = 0
                    P[j][1] = 0
            done.append(i)
        if 0 not in Q:
            break
    if fin == done:
        T = False
        break
if T:
    print('Yes')
    for i in range(2, N+1):
        print(Q[i])
else:
    print('No')

Submission status: Runtime Error

Solution code:
def find_next(room, move):
    for next in path[room]:
        if mark[next] != None:
            if mark[next][1] < move:
                continue
            else:
                mark[next] = (room, move)
                find_next(next, move + 1)
        else:
            mark[next] = (room, move)
            find_next(next, move + 1)

N, M = map(int, input().split())
path = [[] for _ in range(N)]
for i in range(M):
    A_i, B_i = map(int, input().split())
    path[A_i - 1].append(B_i - 1)
    path[B_i - 1].append(A_i - 1)
# print(path)
mark = [None] * N
mark[0] = (0, 0)
find_next(0, 1)
print("Yes")
for i in range(1, len(mark)):
    print(mark[i][0] + 1)

Submission status: Runtime Error

Solution code:
from collections import deque

def main():
    n, m = map(int, input().split())
    ans_list = [0]*(n+1)

    class Node:
        def __init__(self, x):
            self.val = x
            self.adj = []

    nodelist = [Node(0)]
    for i in range(1, n+1):
        nodelist.append(Node(i))

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

    q = deque()
    q.append(nodelist[1])

    while len(q) > 0:
        node = q.popleft()

        if node is not None:
            for i in node.adj:
                if ans_list[i] == 0:
                    ans_list[i] = node.val
                    q.append(nodelist[i])

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

if __name__ = '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

import numpy as np

sys.setrecursionlimit(100000000)


def solve(n, arr, q, path, c):
  flag = True
  for i in path:
    if path[i] == 0:
      flag = False
  if flag:
    return path
  if c > 100000000:
    return -1
  if len(q) == 0:
    return -1
  pos = q.popleft()
  for i in range(1, n):
    if arr[pos][i] == 1:
      q.append(i)
      if path[i+1] == 0:
        path[i+1] = pos+1
  return solve(n, arr, q, path, c+1)
        

def calc(n, arr):
  path = {i:0 for i in range(2, n+1)}
  queue = deque([0])
  result = solve(n, arr, queue, path, 0)
  if result == -1:
    return ["No"]
  else:
    L = ["Yes"]
    for i in result:
      L.append(result[i])
    return L

n, m = map(int, input().split())
arr = np.zeros([n, n])
for i in range(m):
  tmp0, tmp1 = map(int, input().split())
  arr[tmp0-1][tmp1-1] = 1
  arr[tmp1-1][tmp0-1] = 1

answer = calc(n, arr)
for i in answer:
  print(i)

Submission status: Runtime Error

Solution code:
S = input()
N = int(S[0])
M = int(S[2])
P = []
for i in range(M):
    P.append(input().split())
Q = [0]*(N+1)
Q[0] = 1
Q[1] = 1
fin = [1]
done = []
T = True
while 0 in Q:
    for i in fin:
        if i not in done:
            for j in range(M):
                x0 = int(P[j][0])
                x1 = int(P[j][1])
                if x0 == i and Q[x1] == 0:
                    Q[x1] = i
                    if x1 not in fin:
                        fin.append(x1)
                    P[j][0] = 0
                    P[j][1] = 0
                if x1 == i and Q[x0] == 0:
                    Q[x0] = i
                    if x0 not in fin:
                        fin.append(x0)
                    P[j][0] = 0
                    P[j][1] = 0
            done.append(i)
        if 0 not in Q:
            break
    if fin == done:
        T = False
        break
print(T)
if T:
    for i in range(2, N+1):
        print(Q[i])

Submission status: Runtime Error

Solution code:
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while st:
            next_st = set([])
            for n in st:
                if len(AB[n]) == 0:
                    print('No')
                    exit()
                else:
                    for ab in AB[n]:
                        if lst[ab - 1] == 0:
                            lst[ab - 1] = n
                            next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst

    print('Yes')
    [print(i) for i in serch()[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
import networkx as nx

N, M = map(int,input().split())
G = nx.Graph()

for _ in range(M):
    G.add_edge(map(int,input().split()))

print_str = 'Yes\n'
for i in range(2, N + 1):
    ans = nx.shortest_path(G, source = i, target = 1)
    print_str += (str(ans[1]) + '\n')
        
print(print_str[:-1])

Submission status: Runtime Error

Solution code:
def find_next(room, move):
    for next in path[room]:
        if mark[next] != None:
            if mark[next][1] < move:
                continue
            else:
                mark[next] = (room, move)
                # find_next(next, move + 1)
        else:
            mark[next] = (room, move)
            find_next(next, move + 1)

N, M = map(int, input().split())
path = [[] for _ in range(N)]
for i in range(M):
    A_i, B_i = map(int, input().split())
    path[A_i - 1].append(B_i - 1)
    path[B_i - 1].append(A_i - 1)
# print(path)
mark = [None] * N
mark[0] = (0, 0)
find_next(0, 1)
if None in mark:
    print("No")
else:
    print("Yes")
    for i in range(1, len(mark)):
        print(mark[i][0] + 1)

Submission status: Runtime Error

Solution code:
def find_next(room, move):
    for next in path[room]:
        if mark[next] != None:
            if mark[next][1] < move:
                continue
            else:
                mark[next] = (room, move)
                find_next(next, move + 1)
        else:
            mark[next] = (room, move)
            find_next(next, move + 1)

N, M = map(int, input().split())
path = [[] for _ in range(N)]
for i in range(M):
    A_i, B_i = map(int, input().split())
    path[A_i - 1].append(B_i - 1)
    path[B_i - 1].append(A_i - 1)
mark = [None] * N
mark[0] = (0, 0)
find_next(0, 1)
if None in mark:
    print("No")
else:
    print("Yes")
    for i in range(1, len(mark)):
        print(mark[i][0] + 1)

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
R = {}
result = [0]*N
log = [0]*N
for i in range(N):
    R[i+1] = []
for i in range(M):
    A, B = map(int, input().split())
    R[A].append(B)
    R[B].append(A)

def deep(room, depth):
    for next in R[room]:
        if (log[next-1]==0) or (log[next-1]) > depth:
            result[next-1] = room
            log[next-1] = depth
            deep(next, depth+1)
deep(1,1)

if all(r != [] for r in R.values()):
    print("Yes")
    for i in result[1:]:
        print(i)
else:
    print("No")

Submission status: Runtime Error

Solution code:
def find_next(room: int, move: int) -> None:
    for next in path[room]:
        if mark[next] != None:
            if mark[next][1] <= move:
                continue
            else:
                mark[next] = (room, move)
                find_next(next, move + 1)
        else:
            mark[next] = (room, move)
            find_next(next, move + 1)


N, M = map(int, input().split())
path = [[] for _ in range(N)]
for i in range(M):
    A_i, B_i = map(int, input().split())
    path[A_i - 1].append(B_i - 1)
    path[B_i - 1].append(A_i - 1)
# print(path)
mark = [None] * N
mark[0] = (0, 0)
find_next(0, 1)
if None in mark:
    print("No")
else:
    print("Yes")
    for i in range(1, len(mark)):
        print(mark[i][0] + 1)

Submission status: Runtime Error

Solution code:
import collections

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

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

queue = collections.deque([0])
visited = [-1]*N
visited[0] = 0
while queue:
    x = queue.popleft()
    for i in G[x]:
        if visited[i] == -1:
            visited[i] = visited[x] + 1
            queue.append(i)

print("Yes")
print(*visited[1:], sep="\n")

Submission status: Runtime Error

Solution code:
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
    	while st:
            next_st = set([])
            for n in st:
                if len(AB[n]) == 0:
                    print('No')
                    exit()
                else:
                    for ab in AB[n]:
                        if lst[ab - 1] == 0:
                            lst[ab - 1] = n
                            next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst

    print('Yes')
    [print(i) for i in serch()[1:]]
    
if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Runtime Error

Solution code:
import collections

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

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

queue = collections.deque([0])
visited = [0]*N
visited[0] = 1
while queue:
    x = queue.popleft()
    for i in G[x]:
        if visited[i] == 0:
            visited[i] = x + 1
            queue.append(i)
print("Yes")
print(*visited[1:], sep="\n")

Submission status: Runtime Error

Solution code:
from fractions import Fraction
import math

n = int(input())


ab = []
ba = []

a0 = 0
b0 = 0
ab0 = 0

for i in range(n):
    a, b = map(int, input().split())
    if a != 0 and b != 0:
        ab.append(Fraction(a, b))
        ba.append(Fraction(-b, a))
    elif a == 0 and b == 0:
        ab0 += 1
    elif a == 0 and b != 0:
        a0 += 1
    elif a != 0 and b == 0:
        b0 += 1


d_ab = dict()
d_ba = dict()

d_done = dict()

for i in range(len(ab)):
    cur = ab[i]

    if cur in d_ab:
        d_ab[cur] += 1
    else:
        d_ab[cur] = 1

    cur = ba[i]

    if cur in d_ba:
        d_ba[cur] += 1
    else:
        d_ba[cur] = 1

mod = 1000000007

ans = 1

for k, v in d_ab.items():
    x = v
    if k in d_ba:
        if k in d_done:
            continue
        else:
            y = d_ba[k]
            kake = 0
            kake += ((2**x) % mod + (2**y) % mod - 1)
            ans *= kake
            ans %= mod
            d_done[Fraction(-k.denominator, k.numerator)] = 1
    else:
        kake = (2**x) % mod
        ans *= kake
        ans %= mod

ans *= ((2**ab0) % mod)
ans %= mod
ans *= ((2**a0) % mod+(2**b0) % mod-1)
ans %= mod

print(ans-1)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

import numpy as np

sys.setrecursionlimit(100000000)


def solve(n, arr, q, path, c):
  flag = True
  for i in path:
    if path[i] == 0:
      flag = False
  if flag:
    return path
  if c > 100000000:
    return -1
  if len(q) == 0:
    return -1
  pos = q.popleft()
  for i in range(1, n):
    if arr[pos][i] == 1:
      q.append(i)
      if path[i+1] == 0:
        path[i+1] = pos+1
  return solve(n, arr, q, path, c+1)
        

def calc(n, arr):
  path = {i:0 for i in range(2, n+1)}
  queue = deque()
  for i in range(n):
    if arr[0][i] == 1:
      queue.append(i)
      path[i+1] = 1
  result = solve(n, arr, queue, path, 0)
  if result == -1:
    return ["No"]
  else:
    L = ["Yes"]
    for i in result:
      L.append(result[i])
    return L

n, m = map(int, input().split())
arr = np.zeros([n, n])
for i in range(m):
  tmp0, tmp1 = map(int, input().split())
  arr[tmp0-1][tmp1-1] = 1
  arr[tmp1-1][tmp0-1] = 1

answer = calc(n, arr)
for i in answer:
  print(i)

Submission status: Runtime Error

Solution code:
N, M = [int(x) for x in input().split()]


route = {}

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

    if A in route:
        route[A].append(B)
    else:
        route[A] = [B]    

    if B in route:
        route[B].append(A)
    else:
        route[B] = [A]  

step = {}
stepcount = 0
mark = {1: 0}
r = 1

def check(stepcount, r):
    global mark
    stepcount += 1
    if r in route:
        for nextr in route[r]:
            # print(nextr)
            # print(route[nextr])
            if nextr in step:
                # 既存のルートが有る
                # if step[nextr] > stepcount:
                #     # 今回のルートのほうが近い
                #     step[nextr] = stepcount
                #     mark[nextr] = r
                pass
            else:
                # ルートが無い
                step[nextr] = stepcount
                mark[nextr] = r
                check(stepcount, nextr)

check(0, 1)

# print(route)
if len(mark) == N:
    print('Yes')
    for i in range(2, N + 1):
        print(mark[i])
else:
    print('No')

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
#import math
#import itertools
#import re
#from functools import lru_cache
 
input = sys.stdin.readline
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
 
 
def main():
    n, m = list(map(int, input().split()))
    AB = [list(map(int, input().split())) for _ in range(m)]
    graph = [[] for _ in range(n)]
    for a, b in AB:
        graph[a-1].append(b)
        graph[b-1].append(a)
    dist = np.ones(n)
    dist *= -1
    dist[0] = 0
    queue = [[1]]
    while True:
        positions = queue.pop()
        for p in positions:
            queue_next = []
            for next in graph[p-1]:
                if dist[next-1] == -1:
                    dist[next-1] = p
                    queue_next.append(next)
        if len(queue_next) == 0:
            break
        queue.append(queue_next)
    if np.count_nonzero(dist == -1) > 0:
        print(c)
    else:
        print('Yes')
        for d in dist[1:]:
            print(int(d))
 
 
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

def resolve():
    N, M = map(int, input().split())
    G = np.zeros((N + 1, N + 1), dtype=np.int64)

    for _ in range(M):
        x, y = map(int, input().split())
        G[x, y] += 1
        G[y, x] += 1
    csr = csr_matrix(G)
    dist, pred = dijkstra(csgraph=csr, indices=1, return_predecessors=True, directed=False)

    ans = pred[2:]
    impos = any(ans >= 0)
    if impos:
        print("Yes")
        print(*ans, sep="\n")
    else:
        print("No")

if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
# = int(input())
N, M = map(int, input().split())
# = list(map(int, input().split()))
# = [int(input()) for i in range(N)]
AB = [list(map(int, input().split())) for i in range(M)]
sign = [0]*(N-1)
queue = []

for i in range(M):
    if AB[i][0] == 1:
        queue.append(AB[i][1])
        sign[B[i][1]-2] = 1
    elif AB[i][1] == 1:
        queue.append(AB[i][0])
        sign[B[i][0]-2] = 1
    
for i in range(N):
    for j in range(M):
        if AB[i][0] == queue[0] and sign[AB[i][1]-2] == 0:
            queue.append(AB[i][1])
            sign[B[i][1]-2] = queue[0]
        elif AB[i][1] == queue[0] and sign[AB[i][0]-2] == 0:
            queue.append(AB[i][0])
            sign[B[i][0]-2] = queue[0]
    queue.pop(0)

if sign.count(0) > 0:
    print("No")
else:
    print("Yes")
    for number in sign:
        print(number)

Submission status: Runtime Error

Solution code:
from collections import deque

import numpy as np


def solve(n, arr, q, path, c):
  flag = True
  for i in path:
    if path[i] == 0:
      flag = False
  if flag:
    return path
  if c > 100000000:
    return -1
  if len(q) == 0:
    return -1
  pos = q.popleft()
  for i in range(1, n):
    if arr[pos][i] == 1:
      q.append(i)
      if path[i+1] == 0:
        path[i+1] = pos+1
  return solve(n, arr, q, path, c+1)
        

def calc(n, arr):
  path = {i:0 for i in range(2, n+1)}
  queue = deque()
  for i in range(n):
    if arr[0][i] == 1:
      queue.append(i)
      path[i+1] = 1
  result = solve(n, arr, queue, path, 0)
  if result == -1:
    return ["No"]
  else:
    L = ["Yes"]
    for i in result:
      L.append(result[i])
    return L

n, m = map(int, input().split())
arr = np.zeros([n, n])
for i in range(m):
  tmp0, tmp1 = map(int, input().split())
  arr[tmp0-1][tmp1-1] = 1
  arr[tmp1-1][tmp0-1] = 1

answer = calc(n, arr)
for i in answer:
  print(i)

Submission status: Runtime Error

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

ans_li = [-1]*n
queue=deque([0])
visited = [False]*n

while queue:
    x = queue.pop(0)
    for g in map_li[x]:
        if visited[g]==False:
            queue.append(g)
            if ans_li[g]==-1:
                ans_li[g]=x
                visited[g]=True 
if -1 in ans_li[1:]:
    print('No')
else:
    print('Yes')
    for ans in ans_li[1:]:
        print(ans+1)

Submission status: Runtime Error

Solution code:
n,m = map(int, input().split())		# 5 7 2


X = [0]*(n+1)


G = [ [] for _ in range(m+1) ]
for _ in range(m):
	a,b = map(int, input().split())		# 5 7 2
	G[a].append(b)
	G[b].append(a)


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

while Q:
	fm = Q.popleft()
	
	for to in G[fm]:
		
		if X[to]==0:
			X[to] = fm
			Q.append(to)


print("Yes")
for x in X[2:]:
	print(x)

Submission status: Runtime Error

Solution code:
#-------------------------------------------------------------------
import sys
def p(*_a):
  _s=" ".join(map(str,_a))
  #print(_s)
  sys.stderr.write(_s+"\n")
#-------------------------------------------------------------------
n,m = map(int, input().split())		# 5 7 2


X = [0]*(n+1)


G = [ [] for _ in range(m+1) ]
for _ in range(m):
	a,b = map(int, input().split())		# 5 7 2
	G[a].append(b)
	G[b].append(a)


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

while Q:
	fm = Q.popleft()
	
	for to in G[fm]:
		
		if X[to]==0:
			X[to] = fm
			Q.append(to)


print("Yes")
for x in X[2:]:
	print(x)

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
d = deque()
As = [0] * m
Bs = [0] * m
Cs = [0] * (n + 1)  # 標

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


def solver(i):
    aindexs = [j for j, x in enumerate(As) if x == i]
    bindexs = [j for j, x in enumerate(Bs) if x == i]
    for aindex in aindexs:
        target = Bs[aindex]
        d.append(target)
        if Cs[target] == 0:
            Cs[target] = i
    for bindex in bindexs:
        target = As[bindex]
        d.append(target)
        if Cs[target] == 0:
            Cs[target] = i


d.append(1)

while d:
    solver(d.popleft())

for i in range(2, n + 1):
    if (Cs[i] == 0):
        print('No')
        exit()
print('Yes')
for i in range(2, n + 1):
    print(Cs[i])

Submission status: Runtime Error

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,m = mi()

rt = [[] for i in range(n)]
srb = [None] * n
dk = [10**10]*n


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

from collections import deque
l = deque()

srb[0] = 0
for i in rt[0]:
    l.append(i)
    srb[i] = 1

while len(l) != 0:
    print(l)
    c = l.popleft()
    for i in rt[c]:
        if srb[i] == None:
            l.append(i)
            srb[i] = c+1

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

Submission status: Runtime Error

Solution code:
import numpy as np

N, M = [int(i) for i in input().split()]
route = np.zeros([N, N])
for _ in range(M):
    A,B = [int(i) for i in input().split()]
    route[A-1, B-1] = 1
    route[B-1, A-1] = 1
op = np.zeros([N])
for i in range(N):
    if route[0][i] == 1:
        op[i] = 1
for j in range(N):
    if op[j] != 0:
        for k in range(N):
            if route[j][k] == 1:
                if op[k] == 0:
                    op[k] = j+1
flag = 0
for i in op:
    if i == 0:
        print("No")
        flag = 1
        break
if flag == 0:
    print("Yes")
    for i in range(len(op) - 1):
        print(int(op[i+1]))

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
PATHS = list([tuple(map(lambda t: int(t) - 1, input().split())) for i in range(M)])

depths = [None] * N
guides = [None] * N

def func(cuurent, paths, depth):
    depths[cuurent] = depth

    next_rooms = []
    ls_ex = []

    for r1, r2 in paths:
        if r1 == cuurent or r2 == cuurent:
            if r2 == cuurent:
                cuurent, r2 = r2, r1

            if depths[r2] == None or depths[r2] > depth + 1:
                depths[r2] = depth + 1
                guides[r2] = cuurent
                next_rooms.append(r2)
        
        else:
            ls_ex.append((r1, r2))
    
    for room in ls:
        func(room, ls_ex, depth + 1)

func(0, PATHS, 0)

#if not all([follow_guide(i, guides) == depths[i] for i in range(1, N)]):
if False:
    print("No")

else:
    print("Yes")

    for i in guides[1:]:#
        print(i + 1)

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
adjacent_list = [[] for i in range(n+1)]
for i in range(m):
    a, b = map(int, input().split())
    adjacent_list[a].append(b)
    adjacent_list[b].append(a)
ans = [-1 for i in range(n+1)]
def bfs():
    #start at 1
    que = deque([1])
    while que:
        node = que.popleft()
        finished.add(node)
        for i in adjacent_list[node]:
            if ans[i] == -1:
                que.append(i)
                ans[i] = node
bfs()
print("Yes")
for i in range(2,n+1):
    print(ans[i])

Submission status: Runtime Error

Solution code:
N, M = [int(x) for x in input().split()]


route = {}

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

    if A in route:
        route[A].append(B)
    else:
        route[A] = [B]    

    if B in route:
        route[B].append(A)
    else:
        route[B] = [A]  

step = {}
stepcount = 0
mark = {1: 0}
r = 1

def check(stepcount, r):
    global mark
    stepcount += 1
    if r in route:
        for nextr in route[r]:
            # print(nextr)
            # print(route[nextr])
            if nextr in step:
                # 既存のルートが有る
                if step[nextr] > stepcount:
                    # 今回のルートのほうが近い
                    step[nextr] = stepcount
                    mark[nextr] = r
            else:
                # ルートが無い
                step[nextr] = stepcount
                mark[nextr] = r
                check(stepcount, nextr)

check(0, 1)

Submission status: Runtime Error

Solution code:

n, m = map(int, input().split())
table = [[] for i in range(n+1)]
ans = [(1e9, 0) for i in range(n+1)]
def func(node, num, li):
    for i in li:
        if num < n:
            if num < ans[i][0]:
                ans[i] = (num, node)
                func(i, num+1, table[i])
            # print(ans[2:])


# print(table)
for i in range(m):
    a, b = map(int, input().split())
    # print(table[min(a, b)])
    # table[min(a, b)].append(max(a, b))
    table[a].append(b)
    table[b].append(a)

# print(table)


num = 1



func(1, num, table[1])
# print(ans[2:])
ans_ = []
for i in ans[2:]:
    ans_.append(i[1])
# print(ans_)
if 1e9 in ans_:
    print("No")
else:
    print("Yes")
    for i in ans_:
        print(i)


# print(table)

Submission status: Runtime Error

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

# from math import gcd
from fractions import gcd
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
from bisect import bisect_left, bisect_right, bisect, insort_left, insort_right, insort
from itertools import accumulate, product, permutations, combinations, combinations_with_replacement
import copy

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

goal = 1
rets = []
road = {i:[] for i in range(1, N+1)}

for A, B in AB:
    road[A] += [B]
    road[B] += [A]

if not road[1]:
    print("No")
    exit()

retdict = {i:0 for i in range(1, N+1)}
retdict_dis = {i:1000000 for i in range(1, N+1)}

def dfs(bef, mark, ind, dis):

    global retdict, retdict_dis
    if mark[ind] == 1:
        return

    mark[ind] = 1
    if retdict_dis[ind] > dis:
        retdict[ind] = bef
        retdict_dis[ind] = dis

    bef = ind
    dis += 1

    for i in road[ind]:
        dfs(bef, dict.copy(mark), i, dis)

dfs(0, {i:0 for i in range(1, N+1)}, 1, 0)

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

Submission status: Runtime Error

Solution code:
N, M = [int(x) for x in input().split()]


route = {}

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

    if A in route:
        route[A].append(B)
    else:
        route[A] = [B]    

    if B in route:
        route[B].append(A)
    else:
        route[B] = [A]  

step = {}
stepcount = 0
mark = {1: 0}
r = 1

def check(stepcount, r):
    global mark
    stepcount += 1
    if r in route:
        for nextr in route[r]:
            # print(nextr)
            # print(route[nextr])
            if nextr in step:
                # 既存のルートが有る
                if step[nextr] > stepcount:
                    # 今回のルートのほうが近い
                    step[nextr] = stepcount
                    mark[nextr] = r
            else:
                # ルートが無い
                step[nextr] = stepcount
                mark[nextr] = r
                check(stepcount, nextr)

check(0, 1)

# print(route)
if len(mark) == N:
    print('Yes')
    for i in range(2, N + 1):
        print(mark[i])
else:
    print('No')

Submission status: Runtime Error

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

for i in range(m):
    ta, tb = map(int, input().split())
    dir[ta].append(tb)
    dir[tb].append(ta)

ans = [0]*(n+1)
flag = [False]*(n+1)
flag[1] = True
que = deque([1])
while que:
    #print('que: ', len(que), que)
    now = que.popleft()
    for to in dir[now]:
        if flag[to]:
            continue
        que.append(to)
        flag[to] = True
        ans[to] = now
"""         print(to)
        ans[to] = now
        flag[to] = 1
        for toto in dir[to]:
            if flag[toto] != 1:
                que.append(toto) """
print('Yes')
for i in range(2,n+1):
    print(ans[i])

Submission status: Runtime Error

Solution code:
from collections import deque
from collections import defaultdict
import math
import sys

def bfs(queue, visited):
    while len(queue) > 0:
        dest = queue.popleft()
        for i in G[dest]:
            if visited[i] == -1:
                visited[i] = visited[dest] + 1
                queue.append(i)
    return visited
# k = int(input())
# s =input()
# a = list(map(int, input().split()))
n,m= map(int, input().split())
G = defaultdict(set) 
for i in range(m):
    x,y= map(int,input().split())
    G[x].add(y)
    G[y].add(x)

print("Yes")
visited = [-1]*(n+1)
visited[1] = 0
q = deque([1])
visited = bfs(q,visited)


for i,j in enumerate(visited[2:]):
    if j not in deep:
        deep[j]={i+2}
    else:
        deep[j].add(i+2)

for i in range(2,n+1):
    d = visited[i]
    if d == 1:
        print(1)
    else:
        for j in deep[d-1]:
            if j in G[i]:
                print(j)
                break

Submission status: Runtime Error

Solution code:

n, m = map(int, input().split())
table = [[] for i in range(n+1)]
ans = [(1e9, 0) for i in range(n+1+2)]
def func(node, num, li):
    for i in li:
        if num < ans[i][0]:
            ans[i] = (num, node)
            func(i, num+1, table[i])
        # print(ans[2:])


# print(table)
for i in range(m):
    a, b = map(int, input().split())
    # print(table[min(a, b)])
    # table[min(a, b)].append(max(a, b))
    table[a].append(b)
    table[b].append(a)

# print(table)


num = 1



func(1, num, table[1])
# print(ans[2:])
ans_ = []
for i in ans[2:]:
    ans_.append(i[1])
# print(ans_)
if 1e9 in ans_:
    print("No")
else:
    print("Yes")
    for i in ans_:
        print(i)


# print(table)