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:
from collections import deque
import sys
sys.setrecursionlimit(8000)
N, M = map(int, input().split())
graph = [[] for j in range(M)]
q = deque([])
depth_array = [-1 for i in range(N)]

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

def bfs(graph, q, depth_array):
    # 終了条件
    if len(q) == 0:
        return depth_array

    cur_room = q.popleft()

    # キューに追加
    for r in graph[cur_room]:
        if depth_array[r] == -1: #未訪問なら
            q.append(r)
            depth_array[r] = depth_array[cur_room] + 1

    return bfs(graph, q, depth_array)
    
# init
q.append(0)
depth_array[0] = 0
depth_array = bfs(graph, q, depth_array)

mark_array = [-1 for i in range(N)]
#print(depth_array)

for room, depth in enumerate(depth_array):
    for node in graph[room]:
        if depth_array[node] + 1 == depth_array[room]:
            mark_array[room] = node
if -1 in mark_array[1:]:
    print("No")
else:
    print("Yes")
    for m in mark_array[1:]:
        print(m+1)

Submission status: Runtime Error

Solution code:
import queue
N, M = map(int, input().split())
adj = [[] for i in range(N+1)]
parent = [-1] * (N+1)
for m in range(N):
    a, b  = mpa(int, input().split())
    adj[a].append(b)
    adj[b].append(a)
q = queue.Queue()
q.put((1,0))
while(not q.empty()):
    x, p = q.get()
    if parent[x] != -1:
        continue
    parent[x] = p
    for next in adj[x]:
        if parent[next] == -1:
            q.put((next, x))
print("Yes")
for p in parent[2:]:
    print(p)

Submission status: Runtime Error

Solution code:
num_room, num_path = map(int, input().split())

room_paths_dict = {}

start_room_to_paths = set()
result = {}

def solve():
    for i in range(num_path):
        a_room_num, b_room_num = map(int, input().split())
        if a_room_num == 1:
            start_room_to_paths.add(b_room_num)
            continue
        elif b_room_num == 1:
            start_room_to_paths.add(a_room_num)
            continue

        result[a_room_num] = 0
        result[b_room_num] = 0

        if not room_paths_dict.get(a_room_num):
            room_paths_dict[a_room_num] = set()
        if not room_paths_dict.get(b_room_num):
            room_paths_dict[b_room_num] = set()

        room_paths_dict[a_room_num].add(b_room_num)
        room_paths_dict[b_room_num].add(a_room_num)
    if len(start_room_to_paths) == 0:
        print('No')
        return

    def search(room_num):
        targets = []
        for next_room in room_paths_dict[room_num]:
            if result[next_room] == 0:
                result[next_room] = room_num
                targets.append(room_num)

        for t in targets:
            search(t)

    for start_room_to_path in start_room_to_paths:
        result[start_room_to_path] = 1
        search(start_room_to_path)

    if 0 in result.values():
        print('No')
    else:
        print('Yes')
        for key in sorted(result.keys()):
            print(result[key])

solve()

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(4000)
N, M = map(int, input().split())
graph = [[] for j in range(M)]
q = deque([])
depth_array = [-1 for i in range(N)]

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

def bfs(graph, q, depth_array):
    # 終了条件
    if len(q) == 0:
        return depth_array

    cur_room = q.popleft()

    # キューに追加
    for r in graph[cur_room]:
        if depth_array[r] == -1: #未訪問なら
            q.append(r)
            depth_array[r] = depth_array[cur_room] + 1

    return bfs(graph, q, depth_array)
    
# init
q.append(0)
depth_array[0] = 0
depth_array = bfs(graph, q, depth_array)

mark_array = [-1 for i in range(N)]
#print(depth_array)

for room, depth in enumerate(depth_array):
    for node in graph[room]:
        if depth_array[node] + 1 == depth_array[room]:
            mark_array[room] = node
if -1 in mark_array[1:]:
    print("No")
else:
    print("Yes")
    for m in mark_array[1:]:
        print(m+1)

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(2000)
N, M = map(int, input().split())
graph = [[] for j in range(M)]
q = deque([])
depth_array = [-1 for i in range(N)]

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

def bfs(graph, q, depth_array):
    # 終了条件
    if len(q) == 0:
        return depth_array

    cur_room = q.popleft()

    # キューに追加
    for r in graph[cur_room]:
        if depth_array[r] == -1: #未訪問なら
            q.append(r)
            depth_array[r] = depth_array[cur_room] + 1

    return bfs(graph, q, depth_array)
    
# init
q.append(0)
depth_array[0] = 0
depth_array = bfs(graph, q, depth_array)

mark_array = [-1 for i in range(N)]
#print(depth_array)

for room, depth in enumerate(depth_array):
    for node in graph[room]:
        if depth_array[node] + 1 == depth_array[room]:
            mark_array[room] = node
if -1 in mark_array[1:]:
    print("No")
else:
    print("Yes")
    for m in mark_array[1:]:
        print(m+1)

Submission status: Runtime Error

Solution code:
n,m=map(int,input().split())
r=[[] for x in range(n)]
for c in range(m):
    a,b=map(int,input().split())
    r[a-1].append(b-1)
    r[b-1].append(a-1)
s=[-1]*n
u=[0]
k=1
for c in range(10**5):
  v=[]
    for d in u:
        for e in r[d]:
            if s[e]==-1:
                s[e]=d
                k+=1
                v.append(e)
    if k>n-1:
        break
    u=v
print('Yes')
for c in range(n-1):
    print(s[c+1]+1)

Submission status: Runtime Error

Solution code:

def resolve():
  N, M = map(int, input().split(" "))
  AB_map = [[] for i in range(N)]
  for m in range(M):
    AB = [int(x) - 1 for x in input().split(" ")]
    AB_map[AB[0]].append(AB[1])
    AB_map[AB[1]].append(AB[0])

  not_finished = set(range(1, N))
  rooms = [None] * N
  rooms[0] = 0
  room_depths = [0] * N

  def search_and_mark(recent_rooms, depth):
    if len(not_finished) == 0 or depth >= N:
      return True

    temp_recent = set()
    for r in recent_rooms:
      for target in AB_map[r]:
        if target in not_finished:
          temp_recent.add(target)
          not_finished.remove(target)
          rooms[target] = r
          room_depths[target] = depth

    return search_and_mark(list(temp_recent), depth+1)

  _ = search_and_mark([0], 0)

  print("Yes")
  for r in rooms[1:]:
    print(r + 1)


if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
num_room, num_path = map(int, input().split())

room_paths_dict = {}

start_room_to_paths = set()
result = {}

for i in range(num_path):
    a_room_num, b_room_num = map(int, input().split())
    if a_room_num == 1:
        start_room_to_paths.add(b_room_num)
        continue
    elif b_room_num == 1:
        start_room_to_paths.add(a_room_num)
        continue

    result[a_room_num] = 0
    result[b_room_num] = 0

    if not room_paths_dict.get(a_room_num):
        room_paths_dict[a_room_num] = set()
    if not room_paths_dict.get(b_room_num):
        room_paths_dict[b_room_num] = set()

    room_paths_dict[a_room_num].add(b_room_num)
    room_paths_dict[b_room_num].add(a_room_num)

def search(room_num):
    targets = []
    for next_room in room_paths_dict[room_num]:
        if result[next_room] == 0:
            result[next_room] = room_num
            targets.append(room_num)

    for t in targets:
        search(t)

for start_room_to_path in start_room_to_paths:
    result[start_room_to_path] = 1
    search(start_room_to_path)

if 0 in result.values():
    print('No')
else:
    print('Yes')
    for key in sorted(result.keys()):
        print(result[key])

Submission status: Runtime Error

Solution code:
n,m=map(int,input().split())
r=[[] for x in range(n)]
for c in range(m):
    a,b=map(int,input().split())
    r[a-1].append(b-1)
    r[b-1].append(a-1)
s=[-1]*n
u=[0]
k=1
for c in range(10**5):
  	v=[]
    for d in u:
        for e in r[d]:
            if s[e]==-1:
                s[e]=d
                k+=1
                v.append(e)
    if k>n-1:
        break
    u=v
print('Yes')
for c in range(n-1):
    print(s[c+1]+1)

Submission status: Runtime Error

Solution code:
from collections import deque

N, M = map(int, input().split())
graph = [[] for j in range(M)]
q = deque([])
depth_array = [-1 for i in range(N)]

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

def bfs(graph, q, depth_array):
    # 終了条件
    if len(q) == 0:
        return depth_array

    cur_room = q.popleft()

    # キューに追加
    for r in graph[cur_room]:
        if depth_array[r] == -1: #未訪問なら
            q.append(r)
            depth_array[r] = depth_array[cur_room] + 1

    return bfs(graph, q, depth_array)
    
# init
q.append(0)
depth_array[0] = 0
depth_array = bfs(graph, q, depth_array)

mark_array = [-1 for i in range(N)]
#print(depth_array)

for room, depth in enumerate(depth_array):
    for node in graph[room]:
        if depth_array[node] + 1 == depth_array[room]:
            mark_array[room] = node
if -1 in mark_array[1:]:
    print("No")
else:
    print("Yes")
    for m in mark_array[1:]:
        print(m+1)

Submission status: Runtime Error

Solution code:
from collections import deque

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

q=deque([0])

TFl=[0]*N
TFl[0]=1
ml=[-1]*N

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

while q:
  p = q.popleft()
  for i in l[p]: #普通に1行ずつ回してるイメージ
    if TFl[i]==1:
      continue
    TFl[i]=1
    ml=p
    q.append(i)

if all([i==1 for i in TFl]):
  print('Yes')
  for i in range(1, N):
    print(ml[i]+1)

else:
  print('No')

Submission status: Runtime Error

Solution code:
num_room, num_path = map(int, input().split())

room_paths_dict = {}

start_room_to_paths = []
result = {}

for i in range(num_path):
    a_room_num, b_room_num = map(int, input().split())
    if a_room_num == 1:
        start_room_to_paths.append(b_room_num)
        continue
    elif b_room_num == 1:
        start_room_to_paths.append(a_room_num)
        continue

    result[a_room_num] = 0
    result[b_room_num] = 0

    if not room_paths_dict.get(a_room_num):
        room_paths_dict[a_room_num] = set()
    if not room_paths_dict.get(b_room_num):
        room_paths_dict[b_room_num] = set()

    room_paths_dict[a_room_num].add(b_room_num)
    room_paths_dict[b_room_num].add(a_room_num)

def search(room_num):
    targets = []
    for next_room in room_paths_dict[room_num]:
        if result[next_room] == 0:
            result[next_room] = room_num
            targets.append(room_num)

    for t in targets:
        search(t)

for start_room_to_path in start_room_to_paths:
    result[start_room_to_path] = 1
    search(start_room_to_path)

if 0 in result.values():
    print('No')
else:
    print('Yes')
    for key in sorted(result.keys()):
        print(result[key])

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
import math

N , M = map(int,input().split())
miti = [ [] for _ in range(M)]  
for m in range(M):
    a , b = map(int , input().split())
    if b-1 != 0:
        miti[a-1].append(b-1)
    if a-1 != 0:
        miti[b-1].append(a-1)
visit = [0] * N
point = [ -1 for _ in range(N)]

def bfs():
    nextV = [0]
    visit[0] = 1
    total = 1
    while True:
        G = nextV
        # 次のloop用
        nextV = []
        for m in G:
            # m : 現在地
            # n : 目的地

            # mから到達可能な点nを調べる
            for n in miti[m]:
                if visit[n] == 0 :
                    # first visit
                    visit[n] = 1
                    point[n] = m
                    # 次の探索範囲を追加
                    nextV.append(n)
                    total += 1
                else:
                    continue
        if total == N :
            break

def solve():
    bfs()
    print("Yes")
    for a in point[1::]:
        print(a+1)

if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
import queue
n,m=map(int,input().split())
A=[]
B=[]
c=[0]*(n+1)
for _ in range(m):
    a,b=map(int,input().split())
    A.append(a)
    B.append(b)
q=queue.Queue()
q.put(1)
count=n-1
while not q.empty() and count>0:
    aa=q.get()
    for i in range(m):
        print(aa)
        print(c)
        if A[i]==aa:
            if c[B[i]]==0:
                c[B[i]]=aa
                count-=1
                q.put(B[i])
                B[i]=-1
        elif B[i]==aa:
            if c[A[i]]==0:
                c[A[i]]=aa
                count-=1
                q.put(A[i])
                A[i]=-1
print('Yes')
for i in range(2,n+1):
    print(c[i])

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
import math

N , M = map(int,input().split())
miti = [ [] for _ in range(M)]  
for m in range(M):
    a , b = map(int , input().split())
    if b-1 != 0:
        miti[a-1].append(b-1)
    if a-1 != 0:
        miti[b-1].append(a-1)
visit = [0] * N
point = [ [-1 , -1] for _ in range(N)]

def bfs():
    nextV = [0]
    visit[0] = 1
    while True:
        G = nextV
        # 次のloop用
        nextV = []
        cost = +1
        for m in G:
            # m : 現在地
            # n : 目的地

            # mから到達可能な点nを調べる
            for n in miti[m]:
                if visit[n] == 0 :
                    # first visit
                    visit[n] = 1
                    point[n][0] = m
                    point[n][1] = cost
                    # 次の探索範囲を追加
                    nextV.append(n)
                else:
                    continue
        if sum(visit) == N :
            break

def solve():
    bfs()
    print("Yes")
    for a in point[1::]:
        print(a[0]+1)

if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
from sys import stdin
from collections import deque
input = stdin.readline


def main():
    n, m = map(int, input().split())

    nexts = [[] for i in range(n)]
    
    for _ in range(m):
        ai, bi = map(int, input().split())
        ai -= 1
        bi -= 1
        nexts[ai].append(bi)
        nexts[bi].append(ai)

    blues = [m] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues
    checked = [0] * n

    red_deque = deque([0])

    while m in blues:
        rd = red_deque[0]
        red_deque.popleft()
        if checked[rd] == 0:
            checked[rd] = 1
            for nxt in nexts[rd]:
                if blues[nxt] == m:
                    blues[nxt] = rd
                    red_deque.append(nxt)

    print("Yes")
    for blue in blues[1:]:
        print(blue + 1)
    

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
room, route_count = map(int,input().split())
route = np.array([list(map(int,input().split())) for _ in range(route_count)])
 
object_nums = [1]
ans = np.array([0]*(room-1))
 
def mem_ans(ans, object_num, next_nums):
    next_nums = next_nums - 2
    ans[next_nums-2] = object_num
    return ans
 
for object_num in object_nums:
    object_rows = route[np.any(route==object_num, axis=1)]
    route = route[~np.any(route==object_num, axis=1)]
    next_nums = object_rows[object_rows!=object_num]
    
    if next_nums is not None:
        ans = mem_ans(ans, object_num, next_nums)
        object_nums.extend(next_nums)
    else:
        break
print(ans)
if 0 in set(ans):
  print('No')
else:
  print('Yes')
  for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
n,m,x=map(int,input().split())
l=[]
while n>0:
    for i in range(n):
        a=list(map(int,input().split()))
        l.append(a)
        if a[i]

Submission status: Runtime Error

Solution code:
import collections
class Graph():
  def __init__(self):
    self.dict = {}
  def add_vertex(self,v):
    self.dict[v] = []
  def add_edge(self,v1,v2):
    self.dict[v1].append(v2)
    self.dict[v2].append(v1)
  def print_graph(self):
    print(self.dict)
  def get_dict(self):
    return self.dict
  def bfs(self,start, visited = None):
    queue = collections.deque([start])
    visited = []
    depth = [(1,1)]
    cnt = 2
    while list(queue) != []:
      current_vertex = queue.popleft()
      visited.append(current_vertex)
      for v in self.dict[current_vertex]:
        if v not in visited and v not in queue:
          depth.append((v,cnt))
          queue.append(v)
      cnt += 1
    return depth

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

graph = Graph()
for i in range(1,m+1):
  graph.add_vertex(i)

for i in range(1,m+1):
  graph.add_edge(a[i],b[i])

depth = graph.bfs(1)
cnt = 0
ans = [0]*(n+1)
for vcheck in depth:
  if vcheck[0] == 1:
    continue
  else:
    for v in depth:
      if v[1] == vcheck[1] - 1:
        if vcheck[0] in graph.get_dict().values():
          print('No')
          break
        else:
          ans[vcheck[0]]=v[0]
          cnt += 1
          if cnt == n - 1:
            print('Yes')
            for i in range(2,n+1):
              print(ans[i])

Submission status: Runtime Error

Solution code:
import queue
# = 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
q = queue.Queue()
graph = []
sign[0] = 1

for i in range(1, N+1):
    List = []
    for j in range(M):
        if AB[j][0] == i:
            List.append(AB[j][1])
        elif AB[j][1] == i:
            List.append(AB[j][0])
    graph.append(List)

for number in graph[0]:
    q.put(number)
    sign[number-1] = 1

for i in range(1, N):
    for j in range(len(graph[q[0]-1])):
        if sign[graph[q[0]-1][j]-1] == 0:
            sign[graph[q[0]-1][j]-1] = q[0]
            q.put(graph[queue[0]-1][j])
    q.get()

sign.pop(0)

print("Yes")
for number in sign:
    print(number)

Submission status: Runtime Error

Solution code:

import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read
inp = sys.stdin.buffer.readline
def inpS(): return inp().rstrip().decode()
readlines = sys.stdin.buffer.readlines
MOD = 10 ** 9 + 7
INF = 1 << 60

# ---------------------------------------------------
# ---------------------------------------------------
# ---------------------------------------------------

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

def resolve():
    N, M = map(int, inp().split())
        
    A = []
    B = []
    for _ in range(M):
        x, y = map(int, inp().split())
        A.append(x)
        B.append(y)
    csr = csr_matrix(([1]*M, (A, B)))
    dist, pred = dijkstra(csgraph=csr, indices=1, directed=False,return_predecessors=True)

    print("Yes")
    [print(d) for d in pred[2:] if d>0]

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
def resolve():
    from scipy.sparse.csgraph import shortest_path
    from scipy.sparse import csr_matrix
    import numpy as np
    n, m = map(int, input().split())
    edge = np.array([input().split() for _ in range(m)], dtype=np.int64).T
    a = csr_matrix(([1] * m, (edge - 1)))
    s, p = shortest_path(a, method='D', return_predecessors=True,
                         indices=0, directed=False, unweighted=True)
    if min(p[1:]) < -1:
        print("No")
    else:
        print("Yes")
        for i in p[1:]:
            print(i + 1)


if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
if __name__ == '__main__':
    n, m = tuple(map(int, input().split()))
    d = {0: [1]}
    d.clear()
    d2 = {1: 0}

    for i in range(0, m):
        t1, t2 = tuple(map(int, input().split()))
        if t1 in d.keys():
            d[t1].append(t2)
        else:
            d[t1] = [t2, ]
        if t2 in d.keys():
            d[t2].append(t1)
        else:
            d[t2] = [t1, ]


    def sig(dest):
        flag = False

        for i in dest:
            for j in d[i]:
                if (not (j in d2.keys())) and (not (j in dest)):
                    flag = True
                    d2[j] = i


        if not flag:
            return
        for i in dest:
            sig(set(d[i]) - set(d2.values()))


    sig([1])
    if len(d) < n:
        print("No")
    else:
        print("Yes")
        for i in range(2, n + 1):
            print(d2[i])

Submission status: Runtime Error

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

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

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

INF = 10 ** 6

def dijkstra_travel(edges):
    dists = [ INF  for _ in range(n) ]
    paths = [ None for _ in range(n) ]

    dists[0] = 0
    paths[0] = 0

    def travel_adjacent(n):
        adjacent_nodes = list(
            map(
                lambda node: (node, paths[node]),
                edges[n],
            )
        )

        next_travel = []

        for node, path in adjacent_nodes:
            if path is None or dists[node] > dists[n] + 1:
                dists[node] = dists[n] + 1
                paths[node] = n
                next_travel.append(node)

        for x in next_travel:
            travel_adjacent(x)

    travel_adjacent(0)

    return paths[1:]

result = dijkstra_travel(edges)

if all(map(lambda x: x is not None, result)):
    print('Yes')

    for x in result:
        print(x + 1)

else:
    print('No')

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
room_adjacent = [[] for _ in range(n)]
for _ in range(m):
  room1, room2 = map(int, input().split())
  room_adjacent[room1-1].append(room2)
  room_adjacent[room2-1].append(room1)

def label_rooms(old_room):
  for room in room_adjacent[old_room-1]:
    if room_labels[room-1] == 0: room_labels[room-1] = old_room
  for room in room_adjacent[old_room-1]:
    if room_labels[room-1] == old_room: label_rooms(room)

room_labels = [1]+[0]*(n-1)
label_rooms(1)
if 0 in room_labels:
  print("No")
else:
  print("Yes")
  [print(value) for value in room_labels[1:]]

Submission status: Runtime Error

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

routes = []
for i in range(m):
    route = list(map(int, input().split()))
    routes.append(route)
    routes[i] = routes[i] - [1,1] #道の番号をずらす

rooms = []
for i in range(n):
    rooms.append(0) # 行ったら1,まだなら0
marks = rooms # 部屋におく道標
roomsrate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1

turn = 0
for i in roomsrate:
    newrate = []
    for j in roomsrate[turn]: #turn回目に行ける部屋を調べる
        for k in range(m):
            a = int(routes[k][0])
            b = int(routes[k][1]) 
            if (j == a and int(rooms[b]) == 0):
                rooms[b] = 1
                marks[b] = a
                newrate.append(b)
            elif (j == b and int(rooms[a]) == 0):
                rooms[a] = 1
                marks[a] = b
                newrate.append(a)
    roomsrate.append(newrate)
    if (len(newrate) == 0):
        break
    turn = turn + 1


if(all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

Submission status: Runtime Error

Solution code:
from collections import deque
import numpy as np


def main():
    n,m = map(int,input().split())
    arr = np.zeros([n, n], dtype=int)
    for _ in range(m):
        a, b = map(int,input().split())
        arr[a-1][b-1] = 1
        arr[b-1][a-1] = 1
    q = deque([0])
    ans = {i:-1 for i in range(n)}
    ans[0] = 0
    while True:
        now = q.popleft()
        for i in range(n):
            if arr[now][i] == 0:
                continue
            if ans[i] == -1:
                ans[i] = now
                q.append(i)
        if len(q) == 0:
            break
    print('Yes')
    for i in range(1,n):
        print(ans[i]+1)


if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import Counter 
from collections import defaultdict
from collections import deque
from functools import reduce
import math
import itertools
import heapq
import numpy as np
import sys
sys.setrecursionlimit(10**6)

#n=int(input())
#n,m=list(map(int,input().split()))
#a=list(map(int,input().split()))
ceil=lambda x,y: (x+y-1)//y
input_list = lambda : list(map(int,input().split()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    check=[False for _ in range(n)]
    check[s]=True
    queue=[n for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    last_ind=1
    while last_ind<n:

        
        if now>=n or queue[now]==n:
            return []

        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if check[edge]:
                continue

            queue[last_ind]=edge
            last_ind+=1
            #check[edge]=True
            
            ans[edge]=queue[now]
            check[edge]=True
        now+=1
        print(queue)
        print(last_ind)
        print()
    return ans



n,m=input_list()
node=[[] for _ in range(n)]
for i in range(m):
    u,v=input_list()
    u-=1
    v-=1
    node[u].append([v,i])
    node[v].append([u,i])

#print(np.array(node))

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

print("Yes")
for each in ans[1:]:
    print(each+1)

Submission status: Runtime Error

Solution code:
from collections import deque

from typing import List
Graph = List[List[int]]

def main():
    n, m = map(int, input().split())
    G : Graph = [[]*n for _ in range(m)]
    for _ in range(m):
        a, b = map(int, input().split())
        G[a-1].append(b)
        G[b-1].append(a)
    print(G)

    #距離の初期化
    limit = 10 ** 5
    dist = {i: limit+1 for i in range(1, n+1)}
    que = deque()

    # 初期条件
    dist[1] = 0
    que.append(1)
    ans = [0]*(n+1)

    # BFS開始
    while len(que) != 0:
        visit : int = que.popleft()

        for next_v in G[visit-1]:
            if dist[next_v] > dist[visit] + 1:
                # 新たな頂点next_vについて距離情報を更新してキューに追加する
                dist[next_v] = dist[visit] + 1
                que.append(next_v)
                ans[next_v] = visit

    if all([i != 0 for i in ans[2:]]):
        print("Yes")
        print(*ans[2:], sep="\n")
    else:print("No")

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
N,M=list(map(int,(input().split())))
sign=[]
for k in range(M):
  A,B=list(map(int,(input().split())))
  sign.append(sorted([A,B]))
len_goal=[[-1,-1] for k in range(N+1)]
# 1番目の部屋の深さを1、行き先1に設定
len_goal[1][0]=1
len_goal[1][1]=1

sign=sorted(sign)

for room in sign:
  # 両方に深さが設定されている場合、深いほうの深さを浅い方+1にして、行き先を浅い方にする
  if(len_goal[room[0]][0]>len_goal[room[1]][0] and len_goal[room[1]][0]>=0):
    len_goal[room[0]][0]=len_goal[room[1]][0]+1
    len_goal[room[0]][1]=room[1]
  # 上に同じ
  elif(len_goal[room[1]][0]>len_goal[room[0]][0] and len_goal[room[0]][0]>=0):
    len_goal[room[1]][0]=len_goal[room[0]][0]+1
    len_goal[room[1]][1]=room[0]

  # 片方にのみ深さが設定されている場合、もう片方の深さを片方+1にして、行き先を片方にする
  elif(len_goal[room[0]][0]<0 and len_goal[room[1]][0]>=0):
    len_goal[room[0]][0]=len_goal[room[1]][0]+1
    len_goal[room[0]][1]=room[1]

  # 上に同じ
  elif(len_goal[room[0]][0]>=0 and len_goal[room[1]][0]<0):
    len_goal[room[1]][0]=len_goal[room[0]][0]+1
    len_goal[room[1]][1]=room[0]
  elif(len_goal[room[0]][0]==-1 and len_goal[room[1]][0]==-1):
    print(1/0)



print("Yes")
for z in len_goal[2:]:
  print(z[1])

Submission status: Runtime Error

Solution code:
import numpy as np
N, M = list(map(int, input().split()))
lis = []
room = np.zeros(N+1)
dep = np.zeros(N+1)
ans = np.zeros(N+1)
for i in range(M):
    a,b=list(map(int, input().split()))
    lis.append((a, b))
    room[a] = room[a]*10 + b
    room[b] = room[b]*10 + a
    
def root(p, c):
  global ans
  global dep
  if (p == 1 or (c != 1 and (dep[c] > dep[p] or dep[c] == 0))):
    dep[c] = dep[p] + 1
    ans[c] = p
    s = str(room[c])
    for i in range(len(s)-2):
      root(c, int(s[i]))
for i in range(len(lis)):
  if lis[i][0] == 1:
    root(1, lis[i][1])
  elif lis[i][1] == 1:
    root(1, lis[i][0])
flag = 1
for i in range(2, N+1):
  if ans[i] == 0:
    flag = 0
if flag == 1:
  print("Yes")
  for i in range(2, N+1):
    print(int(ans[i]))
else:
  print("No")