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:

import math
inf = 10**9


def share_signs(signs, to_room, from_room):
    signs[to_room][1].add(from_room)
    return signs


def update_inf_room(signs, to_room, inf_rooms):
    for inf_room in inf_rooms:
        signs[inf_room][0] = signs[to_room][0] + 1
        signs[inf_room][2] = to_room
    return signs


def change_signs(signs, to_room, from_room):
    """
    1. toの来るリストにfromを追加
    2. fromの行き先にtoを追加
    3. fromの距離を記憶
    4. fromの距離をto+1に変更
    5. もともとのfromの距離がinfならばfromの来るリストもtoに結びつける
        a. fromの来るリスト(fromfrom)の来るリストからfromを削除
        b. 1,2,3,4を行う
    """
    signs[to_room][1].add(from_room)
    signs[from_room][2] = to_room
    from_room_dist = signs[from_room][0]
    signs[from_room][0] = signs[to_room][0] + 1
    if from_room_dist == inf:
        for from_from_room in signs[from_room][1]:
            signs[from_from_room][1].remove(from_room)
            signs = change_signs(signs, from_room, from_from_room)
    return signs


def main():
    n, m, *ab = map(int, open(0).read().split())
    ab = [ab[2 * i:2 * (i + 1)] for i in range(len(ab) // 2)]

    signs = {1: [0, set(), None]}
    for a, b in ab:
        # print(a, b)
        if a in signs or b in signs:
            a_dist = signs.setdefault(a, [inf, set(), None])[0]
            b_dist = signs.setdefault(b, [inf, set(), None])[0]
            # print(a_dist, b_dist)
            if a_dist == b_dist:
                signs = share_signs(signs, a, b)
                signs = share_signs(signs, b, a)
            elif a_dist < b_dist:
                signs = change_signs(signs, a, b)
            else:
                signs = change_signs(signs, b, a)

        else:
            signs[a] = [inf, set(), None]
            signs[b] = [inf, set(), None]
        # print(signs)

    del signs[1]
    signs = sorted(signs.items(), key=lambda x: x[0])
    # print(signs)
    is_yes = all([True if not i[0] == inf else False for _, i in signs])
    if is_yes:
        ans = ['Yes'] + [i[2] for _, i in signs]
    else:
        ans = ['No']
    ans = '\n'.join([str(i) for i in ans])

    print(ans)
    return(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import lil_matrix, csr_matrix
N,M=map(int, input().split())

'''
l=[[0]*N for i in range(N)]
for i in range(M):
  a ,b = map(int, input().split())
  l[a-1][b-1]=1
  l[b-1][a-1]=1
'''

lil = lil_matrix((N, N), dtype=int)
for i in range(M):
  a ,b = map(int, input().split())
  lil[a-1,b-1]=1
  lil[b-1,a-1]=1
l=lil.tocsr()
'''
edge = np.array([input().split() for _ in range(M)], dtype = np.int64).T
graph = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))
'''
dij =dijkstra(l)[0]
ans = []
for i in range(N):
  if not i == 0:
    mitukatta=False
    for j in range(N):
      if l[i][j]==1 and dij[j]==dij[i]-1:
        direc=j
        mitukatta=True
    if not mitukatta:
      print("No")
      sys.exit()
    ans.append(direc+1)
print("Yes")
for a in ans:
  print(a)

Submission status: Runtime Error

Solution code:
import sys
n,m = map(int, sys.stdin.readline().rstrip("\n").split())
adj = [[]for i in range(n+1)]
parent = [-1] * (n+1)
for line in sys.stdin:
    a,b = map(int, line.rstrip("\n").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:]: # 部屋2以降の親（前の部屋）
    print(p)

Submission status: Runtime Error

Solution code:
import numpy as np
n,m=map(int,input().split())
r=np.array([list(map(int,input().split())) for _ in range(m)])
start=np.array([1])
done=np.array([1])
ans=np.array([-1]*n)

for _ in range(n-1):
    start_tmp=np.array([])
    for st in start:
        r_st = r[np.any(r==st, axis=1)].flatten()
        r_gl = np.setdiff1d(np.delete(r_st, np.where(r_st == st)), done)
        
        start_tmp=np.unique(np.append(start_tmp, r_gl))
        done=np.unique(np.append(done, r_gl))
        #print(r_gl)
        ans[r_gl-1] = st
        
    start = start_tmp
    #print(ans)
    #print(start, done)
    
    if len(done)==n:
        break
    
print('Yes')
print('\n'.join(map(str, ans[1:])))

Submission status: Runtime Error

Solution code:
import sys
import numpy
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import lil_matrix
N,M=map(int, input().split())

'''
l=[[0]*N for i in range(N)]
for i in range(M):
  a ,b = map(int, input().split())
  l[a-1][b-1]=1
  l[b-1][a-1]=1
'''
lil = lil_matrix((N, N), dtype=int)
for i in range(M):
  a ,b = map(int, input().split())
  lil[a-1,b-1]=1
  lil[b-1,a-1]=1
l=lil.toarray()

dij =dijkstra(l)[0]
ans = []
for i in range(N):
  if not i == 0:
    mitukatta=False
    for j in range(N):
      if l[i][j]==1 and dij[j]==dij[i]-1:
        direc=j
        mitukatta=True
    if not mitukatta:
      print("No")
      sys.exit()
    ans.append(direc+1)
print("Yes")
for a in ans:
  print(a)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 04:38:30 2020

@author: hiros
"""
import numpy as np
"""
N = 4
M = 4
A = np.array([0,1,2,3])
B = np.array([1,2,3,1])
"""
N,M = map(int,input().split())
A,B = np.zeros(M,dtype=int),np.zeros(M,dtype=int)
for i in range(M):
    A[i],B[i] = map(int,input().split())

A = A-1
B = B-1

ans = np.zeros(N,dtype=int)
ans = ans-1
ans[0]=-2

for i in range(M):
    if (A[i] == 0): #部屋１とつながっている部屋には道しるべ１を置く
        ans[B[i]] = 0
    elif (B[i] == 0):
        ans[A[i]] = 0

flag = 1
deep = 1
room = []
for i in range(N):
    if ans[i]==0:
        room.append(i)  #階層1にある部屋のリスト
room_next = []

while (flag==1):
    for i in room:
        for m in range(M):
            if (A[m]==i and ans[B[m]]==-1):
                ans[B[m]] = i
                room_next.append(B[m])
            elif (B[m]==i and ans[A[m]]==-1):
                ans[A[m]] = i
                room_next.append(A[m])
            else:
                continue
    room = room_next
    flag = 0
    for i in range(N):
        if ans[i] == -1:
            flag = 1
            break   

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

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 04:38:30 2020

@author: hiros
"""
import numpy as np
"""
N = 4
M = 4
A = np.array([0,1,2,3])
B = np.array([1,2,3,1])
"""
N,M = map(int,input().split())
A,B = np.zeros(M,dtype=int),np.zeros(M,dtype=int)
for i in range(M):
    A[i],B[i] = map(int,input().split())

A = A-1
B = B-1

ans = np.zeros(N,dype=int)
ans = ans-1
ans[0]=-2

for i in range(M):
    if (A[i] == 0): #部屋１とつながっている部屋には道しるべ１を置く
        ans[B[i]] = 0
    elif (B[i] == 0):
        ans[A[i]] = 0

flag = 1
deep = 1
room = []
for i in range(N):
    if ans[i]==0:
        room.append(i)  #階層1にある部屋のリスト
room_next = []

while (flag==1):
    for i in room:
        for m in range(M):
            print(ans,room_next)
            if (A[m]==i and ans[B[m]]==-1):
                ans[B[m]] = i
                room_next.append(B[m])
                #print("match,i,m=",i,m)
                #print(room_next)
            elif (B[m]==i and ans[A[m]]==-1):
                ans[A[m]] = i
                room_next.append(A[m])
                #print("match,i,m=",i,m)
                #print(room_next)
            else:
                #print("no match,i,m=",i,m)
                #print("room",room)
                continue
            #print(ans,i,m)
    room = room_next
    print(room_next)
    flag = 0
    for i in range(N):
        if ans[i] == -1:
            flag = 1
            break   

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

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
typedef long long ll;
using namespace std;

vector<vector<int>> to(100005);

void dfs(vector<int> &d, queue<int> &q) {
    while (!q.empty()) {
        int current = q.front();
        q.pop();
        for (int v:to[current]) {
            if (d[v] != -1) continue;
            d[v] = d[current] + 1;
            q.push(v);
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    int a, b;
    rep(i, m) {
        cin >> a >> b;
        a--;
        b--;
        to[a].push_back(b);
        to[b].push_back(a);
    }

    vector<int> d(n + 5, -1);
    queue<int> q;
    q.push(0);
    d[0] = 0;
    dfs(d, q);

    bool ok = true;
    rep(i, n) {
        if (i == 0) continue;
        if (d[i] == -1) ok = false;
    }
    cout << (ok ? "Yes" : "No") << endl;

    rep(i, n) {
        if (i == 0) continue;
        cout << d[i] << endl;
    }
    return 0;
}

Submission status: Runtime Error

Solution code:
(n,m),*e=[[*map(int, t.split())] for t in input()]
t=[[]for _ in range(n+1)]
for a,b in e:t[a]+=[b];t[b]+=[a]
q=[1]
a=[0]*-~n
while q:q=[a[j]==0and(a.__setitem__(j,i)or j)for i in q for j in t[i]]
print('Yes',*a[2:])

Submission status: Runtime Error

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:
    print(d)
    print(dist)
    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('Yes')
print(*ans,sep='\n')

Submission status: Runtime Error

Solution code:
from collections import deque

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

graph=[[] for i in range(n)]

roomSign=[-1]*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])

while D:
    v=D.popleft()
    for i in graph[v]:
        if roomSign[i] == -1:
          roomSign[i]=v
          D.append(i)
          print(roomSign)

print("Yes")

for i in range(1,n):
    print(roomSign[i]+1)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
N, M = map(int, input().split())
m = [list(map(int, input().split())) for _ in range(M)]
 
G = [[] for _ in range(N + 1)]
for a, b in zip(m, m):
    G[a].append(b)
    G[b].append(a)
 
par = [0] * (N + 1)
visited = [0] * (N + 1)
root = 1
visited[root] = 1
q = deque([root])
while q:
    v = q.popleft()
    for w in G[v]:
        if visited[w]:
            continue
        visited[w] = 1
        par[w] = v
        q.append(w)
 
print('Yes')
print(*par[2:], sep='\n')

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M = map(int, input().split())
m = [list(map(int, input().split())) for _ in range(m)]
 
G = [[] for _ in range(N + 1)]
for a, b in zip(m, m):
    G[a].append(b)
    G[b].append(a)
 
par = [0] * (N + 1)
visited = [0] * (N + 1)
root = 1
visited[root] = 1
q = deque([root])
while q:
    v = q.popleft()
    for w in G[v]:
        if visited[w]:
            continue
        visited[w] = 1
        par[w] = v
        q.append(w)
 
print('Yes')
print(*par[2:], sep='\n')

Submission status: Runtime Error

Solution code:
import numpy as np
import itertools

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

class Room:
  def __init__(self, num):
    self.num = num
    self.roots = []
    self.kyori = -1
    self.near = 0
    
  def add_root(self, to):
    self.roots.append(to)
  def set_kyori(self, num, kyori):
    if self.kyori == -1 or self.kyori > kyori:
      self.kyori = kyori
      self.near = num
      for r in self.roots:
        if r.num == num:
          continue
        r.set_kyori(self.num, self.kyori+1)

r_list = sorted(np.unique(np.array(list(itertools.chain.from_iterable(root)))))
rooms = {i:Room(i) for i in r_list}

for r in root:
  a, b = rooms[r[0]], rooms[r[1]]
  a.add_root(b)
  b.add_root(a)

rooms[1].set_kyori(0, 0)
for r in rooms.values():
  if r.kyori == -1:
    print('No')
    break
else:
  print('Yes')
  for r in list(rooms.values())[1:]:
    print(r.near)

Submission status: Runtime Error

Solution code:
import heapq

# def heapify(x):
#     for i in range((x)):
#         x[i] = -x[i]
#     heapq.heapify(x)

# def heappush(heap, item):
#     heapq.heappush(heap, -item)

# def heappop(heap):
#     return -heapq.heappop(heap)

# from heapq import heappop, heappush
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


rooms_count, passages_count = map(int, raw_input().split())
matrix = []
for i in range(0, rooms_count):
    matrix.append([])
    for j in range(0, rooms_count):
        matrix[i].append(False)

for j in range(0, passages_count):
    a, b = map(int, raw_input().split())
    matrix[a - 1][b - 1] = True
    matrix[b - 1][a - 1] = True

seen = set()
distance = [10000] * rooms_count
next = [10000] * rooms_count
h = []
heapq.heappush(h, (0, 0, -1))
while len(h):
    (d, room, parent) = heapq.heappop(h)
    if (distance[room] <= d):
        continue
    distance[room] = d
    next[room] = parent
    seen.add(room)

    for neighbor in range(0, rooms_count):
        if neighbor != room and matrix[room][neighbor]:
            heapq.heappush(h, (d + 1, neighbor, room))

if len(seen) == rooms_count:
    print('Yes')
    for room in range(1, rooms_count):
        print(next[room] + 1)
else:
    print('No')

Submission status: Runtime Error

Solution code:
#include <math.h>

#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

#define PI 3.14159265358979323846264338327950L

int main() {
    long double a, b, h, m;
    cin >> a;
    cin >> b;
    cin >> h;
    cin >> m;

    long double theta_a = (h + m / 60.0L) * 30.0L;
    long double theta_b = m * 6.0L;
    long double diff = (theta_a - theta_b) / 180.0L * PI;

    long double c = a * a + b * b - 2 * a * b * cosl(diff);

    printf("%20.20Lf\n", sqrtl(c));

    return 0;
}

Submission status: Runtime Error

Solution code:
import heapq

# def heapify(x):
#     for i in range((x)):
#         x[i] = -x[i]
#     heapq.heapify(x)

# def heappush(heap, item):
#     heapq.heappush(heap, -item)

# def heappop(heap):
#     return -heapq.heappop(heap)

# from heapq import heappop, heappush
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None



n, m = map(int, raw_input().split())
matrix = []
for i in range(0, n):
    matrix.append([])
    for j in range(0, n):
        matrix[i].append(False)

for j in range(0, m):
    a, b = map(int, raw_input().split())
    matrix[a - 1][b - 1] = True
    matrix[b - 1][a - 1] = True

seen = set()
distance = [10000] * m
h = []
heapq.heappush(h, (0, 0))
while len(h):
    (d, room) = heapq.heappop(h)
    if (distance[room] <= d):
        continue
    distance[room] = d
    seen.add(room)

    for neighbor in range(0, n):
        if neighbor != room and matrix[room][neighbor]:
            heapq.heappush(h, (d + 1, neighbor))

if len(seen) == n:
    print('Yes')
    for room in range(1, m):
        print(distance[room])
else:
    print('No')

Submission status: Runtime Error

Solution code:
import heapq

# def heapify(x):
#     for i in range((x)):
#         x[i] = -x[i]
#     heapq.heapify(x)

# def heappush(heap, item):
#     heapq.heappush(heap, -item)

# def heappop(heap):
#     return -heapq.heappop(heap)

# from heapq import heappop, heappush
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None




n, m = map(int, raw_input().split())
matrix = []
for i in range(0, n):
    matrix.append([])
    for j in range(0, n):
        matrix[i].append(False)

for j in range(0, m):
    a, b = map(int, raw_input().split())
    matrix[a - 1][b - 1] = True
    matrix[b - 1][a - 1] = True

seen = set()
distance = [10000] * m
h = []
heapq.heappush((0, 0))
while len(h):
    (d, room) = heapq.heappop(h)
    if (distance[room] <= d):
        continue
    distance[room] = d
    seen.add(room)

    for neighbor in range(0, n):
        if neighbor != room and matrix[room][neighbor]:
            heapq.heappush((d + 1, neighbor))

if len(seen) == n:
    print('Yes')
    for room in range(1, m):
        print(distance[room])
else:
    print('No')

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10000000)
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue

# import fractions

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, M = il()
    AB = {m + 1: [] for m in range(M)}
    for _ in range(M):
        a, b = il()
        AB[a].append(b)
        AB[b].append(a)

    ret = []
    visit = [0] * (N + 1)
    fifoqu = queue.Queue()
    fifoqu.put(1)

    while not fifoqu.empty():
        now = fifoqu.get()
        next = AB[now]
        for n in next:
            if visit[n] != 0:
                continue
            visit[n] = visit[now] + 1
            fifoqu.put(n)
    else:
        if visit[1] == 0:
            print('No')
            exit()
        else:
            visit[1] = 0
            print('Yes')
            for n in range(2, N + 1):
                deep = visit[n]
                rooms = AB[n]
                for room in rooms:
                    if visit[room] == deep - 1:
                        print(room)
                        break


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10000000)
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue

# import fractions

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, M = il()
    AB = {m + 1: [] for m in range(M)}
    for _ in range(M):
        a, b = il()
        AB[a].append(b)
        AB[b].append(a)

    ret = []
    visit = [0] * (N + 1)
    fifoqu = queue.Queue()
    fifoqu.put(1)

    while not fifoqu.empty():
        now = fifoqu.get()
        next = AB[now]
        for n in next:
            if visit[n] != 0:
                continue
            visit[n] = visit[now] + 1
            fifoqu.put(n)
    else:
        if visit[1] == 0:
            print('No')
            exit()
        else:
            visit[1] = 0
            for n in range(2, N + 1):
                deep = visit[n]
                rooms = AB[n]
                for room in rooms:
                    if visit[room] == deep - 1:
                        print(room)
                        break


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

#define endl '\n'

const int N = 1e6;

vector <int> g[N];

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	int n, m;
	cin >> n >> m;
	for(int i=0; i<n; i++) {
		int u, v;
		cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	int p[n+1];
	int seen[n+1];
	memset(seen, 0, sizeof seen);
	queue <int> q; q.push(1); seen[1] = 1;
	while(q.size()) {
		int u = q.front(); q.pop();
		for(int v : g[u]) {
			if(!seen[v]) {
				seen[v] = 1;
				p[v] = u;
				q.push(v);
			}
		}
	}
	int sum = 0;
	for(int i=1; i<=n; i++) sum += seen[i];
	if(sum == n) {
		cout << "Yes" << endl;
		for(int i=2; i<=n; i++) cout << p[i] << endl;
	}
	else cout << "No" << endl;/**/

	return 0;
}

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
L = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    A = a - 1
    B = b - 1
    L[A].append(B)
    L[B].append(A)
BFS = list()
BFS.append([0])
ans = [[] for i in range(n - 1)]
while [] in ans:
    BFS.append([])
    for i in BFS[-2]:
        if L[i]:
            for j in L[i]:
                BFS[-1].append(j)
                ans[j - 1].append(i + 1)
                L[j].remove(i)
print('Yes')
for k in range(len(ans)):
    print(ans[k][0])

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
L = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    A = a - 1
    B = b - 1
    L[A].append(B)
    L[B].append(A)
BFS = list()
BFS.append([0])
ans = [[] for i in range(n - 1)]
while [] in ans:
    BFS.append([])
    for i in BFS[-2]:
        for j in L[i]:
            BFS[-1].append(j)
            ans[j - 1].append(i + 1)
            L[j].remove(i)
print('Yes')
for k in range(len(ans)):
    print(ans[k][0])

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
L = [[] for i in range(n)]
for i in range(m):
    a, b = map(int, input().split())
    A = a - 1
    B = b - 1
    L[A].append(B)
    L[B].append(A)
BFS = list()
BFS.append([0])
ans = [[] for i in range(n - 1)]
while [] in ans:
    BFS.append([])
    for i in BFS[-2]:
        for j in L[i]:
            BFS[-1].append(j)
            ans[j - 1].append(i + 1)
            L[j].remove(i)
for k in range(len(ans)):
    print(ans[k][0])

Submission status: Runtime Error

Solution code:
from collections import deque 

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

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

q = deque()
q.append(1)
ans = [0 for _ in range(N)]

while len(q) > 0:
	v = q.popleft()
	for ike in root[v - 1]:
		q.append(ike)
		if(ans[ike - 1] == 0):
			ans[ike - 1] = v

	root[v-1].clear()

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())

A=[]
B=[]

for _ in range(M):
  n, m = map(int, input().split())
  A.append(n)
  B.append(m)

roomN = ['N' for _ in range(N)]
roomN[0] = 1
roomPN = [0 for _ in range(N)]

for order in range(2, N+1):
  if ! 'N' in roomN:
    break:
  if order-1 in roomN:
     pres = [i+1 for i,x in enumerate(roomN) if x == order-1]
  for pre in pres:
    if pre in A:
      indexs = [i for i,x in enumerate(A) if x == pre]
      for index in indexs:
        now = B[index] -1
        if roomN[now] == 'N':
          roomN[now] = order
          if roomPN[now] == 0:
            roomPN[now] = pre
    if pre in B:
      indexs = [i for i,x in enumerate(B) if x == pre]
      for index in indexs:
        now = A[index] -1
        if roomN[now] == 'N':
          roomN[now] = order
          if roomPN[now] == 0:
            roomPN[now] = pre

print('Yes')
for i in range(1, N):
  print(roomPN[i])

Submission status: Runtime Error

Solution code:
import queue

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

que = queue.Queue()
dist = [float('inf')]*n
pre = [-1]*n

dist[0] = 0
que.put(0)
while q:
  v = q.pop()
  for u in to[v]:
    if dist[u]!=float('inf'):
      continue
    dist[u] = dist[v] + 1
    pre[u] = v
	que.push(u)

print("yes")
for i in range(1, n):
  print(dist[i])

Submission status: Runtime Error

Solution code:
import networkx as nx
N,M = map(int, input().split())
E = [list(map(input().split())) for i in range(M)]

G = nx.Graph() 
G.add_edges_from(E)
di = nx.predecessor(G, source = 1)

print("yes")
for i in range(2,N+1):
  print(di[i][0])

Submission status: Runtime Error

Solution code:
import numpy as np

#まず一行目の"N M"を取得
N,M=map(int, input().split()) 

#2-M+1行目を入力する
arr_path=np.array([0,0])
#空のarrayを値0として定義した
for i in range(M):
    a,b=map(int,input().split())
    arr=np.array([a,b])
    arr_path=np.vstack([arr_path,arr])    

#もはや入れ子構造のリストを使うことにして、level_0のような表現は必要ない
#層の全体を格納するリストのリスト（index0,1,2..と引数に対応して、層0,1,2...と対応する）
class_layer=[]
class_layer.append([1])

#部屋xからの移動先を出力する関数
def transit(x):
    path=arr_path[np.any(arr_path==x, axis=1)]
    #これはいま部屋iを考えている（levelという層にある部屋）
    #pathをarrayから抽出して、その部屋から移動することを考える
    path=path[path != x]
    trans_list=path.tolist()
    return trans_list

#層構造(x層)を1上げて上の層を出力する関数を定義する
def level_up(x):
    now=class_layer[x]
    pre=[]
    if x >=1:
        pre=class_layer[x-1]
    li=[] 
    for i in now:
        for j in transit(i):
            if j in now:
                continue
            elif j in pre:
                continue
            else:
                li.append(j)
    class_layer.append(li)
    
for i in range(M):
    level_up(i)


#1つの部屋に対して、その部屋が何番目の層なのか出力する
def layer_finder(x):
    for i in range(M):
        for j in class_layer[i]:
            if j==x:
                global ans
                ans=i
                #local変数になってしまっていて、関数外でいまいちうまく使えないので、変数を置く前にglobal宣言というものをしてglobal変数にする
                break
            else:
                continue
    return ans


#部屋xが何番の矢印を示せばいいのか出力
def path_get(x):
    #部屋xは層が幾つなのか
    X=layer_dict[x-1]
    #(X-1)層の部屋番号を出力
    li1=class_layer[X-1]
    
    #部屋xからの移動先
    path=arr_path[np.any(arr_path==x, axis=1)]
    path=path[path != x]
    li2=path.tolist()
    
    #l1とl2の共通部分を出す
    #setと&を使うといいらしい!
    li_common=list(set(li1) & set(li2))
    
    print(li_common[0])
    

    
print("yes")
for i in range(2,N+1):
    path_get(i)

Submission status: Runtime Error

Solution code:
#まず一行目の"N M"を取得
N,M=map(int, input().split()) 

#2-M+1行目を入力する
arr_path=np.array([0,0])
#空のarrayを値0として定義した
for i in range(M):
    a,b=map(int,input().split())
    arr=np.array([a,b])
    arr_path=np.vstack([arr_path,arr])    

#もはや入れ子構造のリストを使うことにして、level_0のような表現は必要ない
#層の全体を格納するリストのリスト（index0,1,2..と引数に対応して、層0,1,2...と対応する）
class_layer=[]
class_layer.append([1])

#部屋xからの移動先を出力する関数
def transit(x):
    path=arr_path[np.any(arr_path==x, axis=1)]
    #これはいま部屋iを考えている（levelという層にある部屋）
    #pathをarrayから抽出して、その部屋から移動することを考える
    path=path[path != x]
    trans_list=path.tolist()
    return trans_list

#層構造(x層)を1上げて上の層を出力する関数を定義する
def level_up(x):
    now=class_layer[x]
    pre=[]
    if x >=1:
        pre=class_layer[x-1]
    li=[] 
    for i in now:
        for j in transit(i):
            if j in now:
                continue
            elif j in pre:
                continue
            else:
                li.append(j)
    class_layer.append(li)
    
for i in range(M):
    level_up(i)


#1つの部屋に対して、その部屋が何番目の層なのか出力する
def layer_finder(x):
    for i in range(M):
        for j in class_layer[i]:
            if j==x:
                global ans
                ans=i
                #local変数になってしまっていて、関数外でいまいちうまく使えないので、変数を置く前にglobal宣言というものをしてglobal変数にする
                break
            else:
                continue
    return ans


#部屋xが何番の矢印を示せばいいのか出力
def path_get(x):
    #部屋xは層が幾つなのか
    X=layer_dict[x-1]
    #(X-1)層の部屋番号を出力
    li1=class_layer[X-1]
    
    #部屋xからの移動先
    path=arr_path[np.any(arr_path==x, axis=1)]
    path=path[path != x]
    li2=path.tolist()
    
    #l1とl2の共通部分を出す
    #setと&を使うといいらしい!
    li_common=list(set(li1) & set(li2))
    
    print(li_common[0])
    

    
print("yes")
for i in range(2,N+1):
    path_get(i)