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: Accepted

Solution code:
def dijkstra_heap(graph: list, s: int, V: int=None):
    """
    :param graph: - adjacency list [(v, w), ...]:
    :param s: start
    :param V: number of vertices
    :return: dist, pred
    """
    import heapq

    pq = []
    INF = float("inf")

    if V is None:
        V = len(graph)

    dist = [INF] * V
    pred = [-1] * V

    dist[s] = 0

    heapq.heappush(pq, (0, s))

    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:
            continue

        for v, w in graph[u]:
            new_dist = dist[u] + w
            if new_dist < dist[v]:
                heapq.heappush(pq, (new_dist, v))
                dist[v] = new_dist
                pred[v] = u
    return dist, pred


def main():
    N, M = [int(x) for x in input().split()]
    graph = [list() for _ in range(N)]
    for _ in range(M):
        a, b = [int(x) for x in input().split()]
        a -= 1
        b -= 1
        graph[a].append((b,1))
        graph[b].append((a,1))
    dist, pred = dijkstra_heap(graph, 0)
    if any(d == float("inf") for d in dist):
        print("No")
    else:
        print("Yes")
        for i in range(1,N):
            print(pred[i]+1)
 
 
if __name__ == '__main__':
    import sys
    sys.setrecursionlimit(10000)
    main()

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))

from collections import defaultdict, deque
from sys import exit
import math
import copy
from bisect import bisect_left
from heapq import *
import sys
# sys.setrecursionlimit(1000000)
INF = 10 ** 17
MOD = 998244353

def check(mid, points, origin, rotate):
    height = origin * math.cos(math.radians(rotate))
    # print(height)
    cs = math.cos(math.radians(rotate))
    sn = math.sin(math.radians(rotate))
    for px, py in points:
        py = py - origin
        rx, ry = px*cs - py * sn, px * sn + py * cs
        if abs(rx) > height + 0.0000001 or abs(ry) > height + 0.0000001:
            # print("FALSE", rotate)
            return False

    return True


class Segtree_op():
    def __init__(self, n):
        self.size = 1
        while (n >= 1):
            self.size = self.size << 1
            n = n // 2

        self.arr = [self.unit() for i in range(self.size * 2)]

    def op(self, lch, rch):
        return lch + rch

    def unit(self):
        return 0

    def update(self, k, val):
        k += self.size - 1
        self.arr[k] = val
        while (k):
            k = (k - 1) // 2
            self.arr[k] = self.op(self.arr[k * 2 + 1], self.arr[k * 2 + 2])

    def query(self, l, r):
        L = l + self.size
        R = r + self.size
        s = self.unit()
        while L < R:
            if R & 1:
                R -= 1
                s = self.op(s, self.arr[R - 1])

            if L & 1:
                s = self.op(s, self.arr[L - 1])
                L += 1
            L >>= 1
            R >>= 1
        return s

    def show(self):
        idx = 1
        while (idx <= self.size):
            print(self.arr[idx - 1:idx * 2 - 1])
            idx *= 2


def solve():
    n, m = getList()
    graph = [[] for i in range(n)]
    michi = [-1  for i in range(n)]
    det = [INF for i in range(n)]
    det[0] = 0

    for _ in range(m):
        a, b = getList()
        a, b = a-1, b-1
        graph[a].append(b)
        graph[b].append(a)

    h = []
    for nx in graph[0]:
        heappush(h, (1, nx))
        det[nx] = 1
        michi[nx] = 1

    while(h):
        # print(h)
        _, tgt = heappop(h)
        for nx in graph[tgt]:
            if det[nx] == INF:
                michi[nx] = tgt+1
                det[nx] = det[tgt] + 1
                heappush(h, (det[nx], nx))

    # print(det)
    for d in det:
        if d == INF:
            print("No")
            return
    print("Yes")
    for m in michi[1:]:
        print(m)
def main():
    n = getN()
    for _ in range(n):
        solve()
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(500005)
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, m = na()
g = [[] for _ in range(n)]
for i in range(m):
    a, b = na()
    g[a-1].append(b-1)
    g[b-1].append(a-1)
print("Yes")
q = [0]
ds = [9999999] * n
ds[0] = 0
z = 0
pre = [-1] * n
while z < len(q):
    cur = q[z]
    for e in g[cur]:
        if ds[e] > ds[cur] + 1:
            ds[e] = ds[cur] + 1
            pre[e] = cur
            q.append(e)
    z += 1

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

Submission status: Accepted

Solution code:
from collections import deque

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

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

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

d = [10000000]*n
d[0] = 0
q = deque([0])

prev = [0] * n

while q:
    p = q.popleft()
    for v in g[p]:
        if d[v] == 10000000:
            d[v] = d[p] + 1
            prev[v] = p
            q.append(v)

print("Yes")
for i in range(1, n):
    print(prev[i] + 1)

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    from collections import deque
    input = sys.stdin.readline

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

    que = deque()
    que.append(1)
    seen = [-1] * (N+1)
    seen[1] = 0
    par = [0] * (N+1)
    child = [[] for _ in range(N+1)]
    seq = []
    while que:
        v = que.popleft()
        seq.append(v)
        for u in adj[v]:
            if seen[u] == -1:
                seen[u] = seen[v] + 1
                par[u] = v
                child[v].append(u)
                que.append(u)
    seq.reverse()

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
n,m=map(int,input().split())
G=[[] for i in range(n)]
for i in range(m):
  a,b=map(int,input().split())
  G[a-1].append(b-1)
  G[b-1].append(a-1)
D=deque([0])
V=[0]*n
V[0]=1
P=[0]*n
while len(D)>0:
  x=D[0]
  D.popleft()
  for i in range(len(G[x])):
    if V[G[x][i]]==0:
      V[G[x][i]]=1
      P[G[x][i]]=x+1
      D.append(G[x][i])
print("Yes")
for i in range(1,n):
  print(P[i])

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,m = LI()
    v = [[] for i in range(n)]
    for _ in range(m):
        a,b = LI()
        a -= 1
        b -= 1
        v[a].append(b)
        v[b].append(a)
    q = [(0,0)]
    d = [float("inf")]*n
    d[0] = 0
    pre = [None]*n
    while q:
        dx,x = heappop(q)
        nd = dx+1
        for y in v[x]:
            if nd < d[y]:
                d[y] = nd
                pre[y] = x
                heappush(q,(nd,y))
    if float("inf") in d:
        print("No")
        return
    print("Yes")
    for i in pre[1:]:
        print(i+1)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
from collections import deque

N, M = map(int, input().split())
d = [set() for _ in range(N+1)]
for _ in range(M):
    a, b = map(int, input().split())
    d[a].add(b)
    d[b].add(a)

queue=deque([1])
vs = set([1])
parents = [0] * (N+1)
dist = [0] * (N+1)
while queue:
    v = queue.popleft()
    for u in d[v]:
        if u in vs:
            continue
        parents[u] = v
        vs.add(u)
        queue.append(u)
        dist[u] = dist[v] + 1
print("Yes")
for x in parents[2:]:
    print(x)

Submission status: Runtime Error

Solution code:
from collections import deque

def bfs(s):
  q = deque([s])
  d[s] = 1
  while q:
    node = q.popleft()
    for i in ab[node]:
      if d[i] == 0:
        d[i] = node + 1
        q.append(i)

n,m = map(int, input().split())
ab = [[] for _ in range(n)]
for _ in range(n):
  a,b = map(lambda x: int(x)-1, input().split())
  ab[a].append(b)
  ab[b].append(a)
  
d = [0]*n
bfs(0)
if all(d[1:]):
  print("Yes")
  print(*d[1:], sep="\n")
else: print("No")

Submission status: Runtime Error

Solution code:
from sys import stdin
n,m = map(int, input().split())
li = []
for i in range(n):
    li.append([])
for i in range(m):
    a, b = map(int, stdin.readline().split())
    if a > b:
        a, b = b, a
    if a == 1:
        li[a-1].append(b-1)
    else:
        li[a-1].append(b-1)
        li[b-1].append(a-1)
if len(li[0])==0:
    print("No")
else:
    print("Yes")
    # guide: [[before, kyori]]
    guide = [-1]*n
    dist = [10**8]*n
    dist[0] = 0
    def rec(i):
        # 部屋i と 部屋v をつなぐ道がある
        li_v = li[i]
        for v in li_v:
            if v!=0 and dist[v] > dist[i]+1:
                guide[v] = i
                dist[v] = dist[i] + 1
                rec(v)
    rec(0)

    for i in range(n):
        if i==0:
            continue
        print(guide[i]+1)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(10 ** 6)
def input():
    return sys.stdin.readline()[:-1]

def dfs(v,prev = -1):
    for u in graph[v]:
        if u == prev:
            continue
        sign[u] = v
        dfs(u,v)

def bfs(v):
    que = deque([])
    que.append(v)
    while que:
        p = que.popleft()
        if visited[p] == 0:
            visited[p] = 1
            for u in graph[v]:
                que.append(u)

import heapq

def dijkstra(s):
    hq = [(0, s)]
    heapq.heapify(hq) # リストを優先度付きキューに変換
    cost = [float('inf')] * (M+1) # 行ったことのないところはinf
    cost[s] = 0 # 開始地点は0
    while hq:
        c, v = heapq.heappop(hq)
        if c > cost[v]: # コストが現在のコストよりも高ければスルー
            continue
        for u in graph[v]:
            tmp = 1 + cost[v]
            if tmp < cost[u]:
                cost[u] = tmp
                path[u] = v
                heapq.heappush(hq, (tmp, u))
    return path

N,M = map(int,input().split())
graph = [[] for i in range(M+1)]
for i in range(M):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
path = [0]*(N+1)
c = dijkstra(1)
print("Yes")
for i in range(2,N+1):
    print(c[i])

Submission status: Runtime Error

Solution code:
N,M = map(int,input().split())
X = [list() for _ in range(N)]
ans = []
inf = -1
queue = []
for _ in range(N):
    A,B = map(int,input().split())
    X[A-1].append(B)
    X[B-1].append(A)
#print(X)
x = []
for i in range(1,N):
    queue.append(X[i])
    a = 0
    b = 0
    #print(i,"------------------------")
    while True:
        a += 1
        c = queue.pop()
        if c.count(1) == 1:
            ans.append(a)
            break


        if b == 1:
            ans.append(a)
            break
        for j in c:
            #print(j,X[j-1])
            if X[j-1].count(1) >= 1:
                b = 1
            queue.append(X[j-1])
        #print("queue",queue)
        
print("Yes")
for k in ans:
    print(k)

Submission status: Runtime Error

Solution code:
N,M = map(int,input().split())
X = [list() for _ in range(N)]
ans = []
inf = -1
queue = []
for _ in range(N):
    A,B = map(int,input().split())
    X[A-1].append(B)
    X[B-1].append(A)
#print(X)
x = []
for i in range(1,N):
    queue.append(X[i])
    a = 0
    b = 0
    #print(i,"------------------------")
    while True:
        a += 1
        c = queue.pop()
        if c.count(1) == 1:
            ans.append(a)
            break


        if b == 1:
            ans.append(a)
            break
        for j in c:
            #print(j,X[j-1])
            if X[j-1].count(1) >= 1:
                b = 1
            queue.append(X[j-1])
        #print("queue",queue)
print("Yes")
for k in ans:
    print(k)

Submission status: Runtime Error

Solution code:
N=int(input())
mod=10**9+7
Azero=0
Bzero=0
both=0
plus={}
minus={}
import math
for i in range(N):
  A,B=map(int,input().split())
  if A==0 and B==0:
    both+=1
  elif A==0 and B!=0:
    Azero+=1
  elif A!=0 and B==0:
    Bzero+=1
  else:
    K=math.gcd(A,B)
    A=int(A/K)
    B=int(B/K)
    if A/B>0:
      if A<0:
        A,B=-A,-B
      if (A,B) in plus:
        plus[(A,B)]+=1
      else:
        plus[(A,B)]=1
    else:
      if A<0:
        A,B=-A,-B
      if (A,B) in minus:
        minus[(A,B)]+=1
      else:
        minus[(A,B)]=1

L=[]
if Azero>0 and Bzero>0:
  L.append((Azero,Bzero))
for k,v in plus.items():
  if (k[1],-k[0]) in minus:
    L.append((v,minus[(k[1],-k[0])]))
ans=0
for i in range(len(L)):
  N-=L[i][0]+L[i][1]
N-=both
c=1

for i in range(len(L)):
  c*=(pow(2,L[i][0],mod)+pow(2,L[i][1],mod)-1)
  c%=mod

ans=(c*pow(2,N,mod)-1)%mod

print(ans+both)

Submission status: Runtime Error

Solution code:
from collections import deque

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

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

ans = [-1] * (n - 1)

q = deque()
q.append(0)
used = {0}
while q:
    node = q.popleft()
    for next_node in graph[node]:
        if next_node in used:
          continue
        q.append(next_node)
        used.add(next_node)
        ans[next_node - 1] = node + 1

print('Yes')
print(*ans, sep='\n')

Submission status: Runtime Error

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

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

for i in range(m):
  _, __ = map(int, input().split())
  _ -= 1
  __ -= 1
  adj_list[_].append(__)
  adj_list[__].append(_)
  
distance = [None for i in range(n)]
updated_from = [None for i in range(n)]

newly_visited = deque([0])
distance[0] = 0

while len(newly_visited) > 0:
  now = newly_visited.popleft()
  for i in adj_list[now]:
    if distance[i] is not None: continue
    newly_visited.append(i)
    distance[i] = distance[now] + 1
    updated_from[i] = now

# i に到達できてれば distance[i] ==（0 から i までの距離）
# i に到達できてなければ distance[i] == None   
    
"""
print(distance)

for i in range(n):
  # i から 0 に行く経路を求める
  now = i
  path = [now]
  while now != 0:
    now = updated_from[now]
    path.append(now)
  print(i, path) 
"""

print("Yes")
for i in range(n):
  print(updated_from[i] + 1)

Submission status: Runtime Error

Solution code:
from collections import deque
n,m = map(int,input().split())
l = [list(map(int,input().split())) for i in range(m)]
for i in range(m):
    x,y = l[i][0],l[i][1]
    x,y = x-1,y-1
    if x > y:
        x,y = y,x
    l[i] = [x,y]
l.sort()
print(l)
a,b = deque(),deque()
for i in range(m):
    a.append(l[i][0])
    b.append(l[i][1])
ans = [-1] * n
ans[0] = 0
queue = deque()
for i in range(n):
    queue.append(i)
while queue:
    h = queue.popleft()
    flg = False
    p = 0
    q = len(a)
    while p < q:
        x = a.popleft()
        y = b.popleft()
        if h == x or h == y:
            if ans[x] == -1 and ans[y] == -1:
                a.append(x)
                b.append(y)
                flg = True
            elif ans[x] == -1:
                ans[x] = ans[y] + 1
            elif ans[y] == -1:
                ans[y] = ans[x] + 1
            else:
                ans[x] = min(ans[x],ans[y]+1)
                ans[y] = min(ans[y],ans[x]+1)
        else:
            a.append(x)
            b.append(y)
        p += 1
    if flg:
        queue.append(h)
    print(ans)
if -1 in ans:
    print('No')
else:
    print('Yes')
    for i in ans[1:]:
        print(i)

Submission status: Runtime Error

Solution code:
def main():
	N, M = [int(x) for x in input().split(" ")]
	route = [[] for i in range(N)]
	for i in range(M):
		A, B = [int(y) for y in input().split(" ")]
		route[A - 1] += [B]
		route[B - 1] += [A]

	checked = [1] + [0] * (N - 1)
	to_check = [{"src" : s, "dst" : 1} for s in route[0]]
	signal = [-1] + [0] * (N - 1)
	signal_cnt = 0

	while len(to_check) > 0:
		checking = to_check.pop(0)
		src = checking["src"]
		if checked[src - 1] == 0:
			checked[src - 1] = 1
			signal[src - 1] = str(checking["dst"])
			signal_cnt += 1
			rooms = route[src - 1]
			for r in rooms:
				if checked[r - 1] == 0:
					to_check.append({"src": r, "dst": src})
	if signal_cnt != N - 1
		print("No")
	else:
		print("Yes")
		print("\n".join(signal[1:]))

main()

Submission status: Runtime Error

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

import heapq

def dijkstra(s):
    hq = [(0, s)]
    heapq.heapify(hq) # リストを優先度付きキューに変換
    cost = [float('inf')] * n # 行ったことのないところはinf
    cost[s] = 0 # 開始地点は0
    while hq:
        c, v = heapq.heappop(hq)
        if c > cost[v]: # コストが現在のコストよりも高ければスルー
            continue
        for d, u in e[v]:
            tmp = d + cost[v]
            if tmp < cost[u]:
                cost[u] = tmp
                heapq.heappush(hq, (tmp, u))
    return cost

e = [[] for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    a,b = a-1, b-1
    e[a].append((1, b))
    e[b].append((1, a)) # 有向グラフでは削除

d = dijkstra(0)
# print(d)
ans = [1]*(n)
for i in range(1,n):
    for j in e[i][1]:
        print(i,j)
        if d[j] == d[i] - 1:
            ans[i] = j + 1

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

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
import queue
import sys
imput = sys.stdin.readline

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

conne = [[0]*(n+1) for _ in range(n+1)]
dist = [99999]*(n+1)
par = [0] * (n+1)

for i in range(m):
    a,b = map(int,input().split()) 
    conne[a][b] = 1
    conne[b][a] = 1
    
q=queue.Queue()
dist[1] = 0
q.put((1,0))

while not q.empty():
    
    x,d = q.get()
    
    for i in range(len(conne[x])):
        if conne[x][i]==1 and dist[i]>d+1:
            q.put((i,d+1))
            par[i] = x
            dist[i] = d+1

if max(dist[1:]) == 99999:
    print("No")
    
else:
    print("Yes")    
    
    for i in par[2:]:
        print(i)

Submission status: Runtime Error

Solution code:
import queue
import sys
imput = sys.stdin.readline

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

conne = [[0]*(n+1) for _ in range(m+1)]
dist = [99999]*(n+1)
par = [0] * (n+1)

for i in range(m):
    a,b = map(int,input().split()) 
    conne[a][b] = 1
    conne[b][a] = 1
    
q=queue.Queue()
dist[1] = 0
q.put((1,0))

while not q.empty():
    
    x,d = q.get()
    
    for i in range(len(conne[x])):
        if conne[x][i]==1 and dist[i]>d+1:
            q.put((i,d+1))
            par[i] = x
            dist[i] = d+1

if max(dist[1:]) == 99999:
    print("No")
    
else:
    print("Yes")    
    
    for i in par[2:]:
        print(i)

Submission status: Runtime Error

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

conne = [[0]*(n+1) for _ in range(m+1)]
dist = [99999]*(n+1)
par = [0] * (n+1)

for i in range(m):
    a,b = map(int,input().split()) 
    conne[a][b] = 1
    conne[b][a] = 1
    
q=queue.Queue()
dist[1] = 0
q.put((1,0))

while not q.empty():
    
    x,d = q.get()
    
    for i in range(len(conne[x])):
        if conne[x][i]==1 and dist[i]>d+1:
            q.put((i,d+1))
            par[i] = x
            dist[i] = d+1

if max(dist[1:]) == 99999:
    print("No")
    
else:
    print("Yes")    
    
    for i in par[2:]:
        print(i)

Submission status: Runtime Error

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

conne = [[0]*(n+1) for _ in range(m+1)]
dist = [99999]*(n+1)
par = [0] * (n+1)

for i in range(m):
    a,b = map(int,input().split()) 
    conne[a][b] = 1
    conne[b][a] = 1
    
q=queue.Queue()
dist[1] = 0
q.put((1,0))

while not q.empty():
    
    x,d = q.get()
    
    for i in range(len(conne[x])):
        if conne[x][i]==1 and dist[i]>d+1:
            q.put((i,d+1))
            par[i] = x
            dist[i] = d+1
            
for i in par[2:]:
    print(i)

Submission status: Runtime Error

Solution code:
from collections import deque
n, m = [int(i) for i in input().split()]
edges = [[int(i) for i in input().split()] for _ in range(n)]
tree = [[] for _ in range(n+1)]
for edge in edges:
  tree[edge[0]].append(edge[1])
  tree[edge[1]].append(edge[0])
tree_ = [-1] * (n + 1)
tree_[1] = 0

dq = deque()
dq.append(1)
ans = [0] * (n + 1)
while dq:
  node = dq.popleft()
  for d in tree[node]:
    if tree_[d] != -1:
      continue
    tree_[d] = tree_[node] + 1
    ans[d] = node
    dq.append(d)
print('Yes')
print(*ans[2:], sep='\n')

Submission status: Runtime Error

Solution code:
use proconio::input;
use std::collections::HashMap;
use std::collections::VecDeque;

fn main() {
    input! {
        n: usize,
        m: usize,
        aisles: [(usize, usize); m],
    }

    let mut map : HashMap<usize, Vec<usize>> = HashMap::new();
    let mut guideposts = vec![None ; n+1];

    for aisle in &aisles {
        if let Some(rooms) = map.get_mut(&aisle.0) {
            rooms.push(aisle.1);
        } else {
            map.insert(aisle.0 , vec![aisle.1]);
        }
        if let Some(rooms) = map.get_mut(&aisle.1) {
            rooms.push(aisle.0);
        } else {
            map.insert(aisle.1 , vec![aisle.0]);
        }
    }

    let mut que = VecDeque::new();
    que.push_back(1);

    while !que.is_empty() {
        let now = que.pop_front().unwrap();
        if let Some(rooms) = map.get(&now) {
            for room in rooms {
                if guideposts[*room] == None {
                    guideposts[*room] = Some(now);
                    que.push_back(*room);
                }
            }
        }
    }

    if guideposts.iter().skip(2).all(|x| *x != None) {
        println!("Yes");
        for guidepost in guideposts.iter().skip(2) {
            if let Some(post) = guidepost {
                println!("{}", post);
            }
        }
    } else {
        println!("No");
    }
}

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
def bfs(graph, N, start):
    visited = [0] * N
    visited[start] = 1
    que = deque([start])
    while que:
        node = que.popleft()
        for n in graph[node]:
            if not visited[n]:
                visited[n] = node + 1
                que.append(n)
    return visited

input = sys.stdin.readline

def main():
    N, M = map(int, input().split())

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

    visited = bfs(graph, N, 0)[1:]
    if all(visited):
        print("Yes")
        print(*visited, seq="\n")
    else:
        print("No")


main()

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
N, M = list(map(int, input().split))
ans = [[] * N]
visited = [[False] * N]
dq = deque([0])
path = [[0] * N]
for s in sys.stdin.readlines():
    a, b = map(lambda: int(x)-1, s.split())
    path[a].add(b)
    path[b].add(a)
while dq:
   i = dq.popleft()
   if visited[i]:
      continue
   visited[i] = True
   next_rs = path[i]
   for i in range(len(next_rs)):
      dq.append(next_rs[i])
      ans[next_rs[i]] = i
if sum(visited) == N:
   print('Yes')
   for i in range(N):
      if i == 0:
         continue
      else:
         print(ans[i])
else:
   print(-1)

Submission status: Runtime Error

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

to = [[] for i in range(100010)]

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

dist = [0] * (N+1)
q = [1]

#print(to[:4])

dist = [0] * N
pre = [0] * N

while len(q) != 0:
    a = q.pop(0)
    for i in to[a]:
        if dist[i-1] == 0:
            dist[i-1] = dist[a-1] + 1
            pre[i-1] = a
            q.append(i)
    print(q)

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

Submission status: Runtime Error

Solution code:
# 幅優先探索, BFS

from collections import deque

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

neighbor = [[] for _ in range(m)]
for edge in edges:
    neighbor[edge[0]-1].append(edge[1]-1)  # 1- → 0-index
    neighbor[edge[1]-1].append(edge[0]-1)

queue = deque()
queue.append(0)

back = [-1] * n  # visitしたかどうかを兼ねる
back[0] = 0
while len(queue) > 0:
    vertex = queue.popleft()
    for nei in neighbor[vertex]:
        if back[nei] == -1:
            back[nei] = vertex
            queue.append(nei)
        
print('Yes')
for i in back[1:]:
    print(i+1)  # 0- → 1-index

Submission status: Runtime Error

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

#そこから直で行けるところをまとめる
ikeru = [[] for i in range(N)]
for i in range(M):
    ikeru[AB[i][0]-1].append(AB[i][1]-1)
    ikeru[AB[i][1]-1].append(AB[i][0]-1)
# print('ikeru:',ikeru)



que = deque([])
que.append(0)
# print('que ini:',que)
out=[10**6]*N
out[0]=0

while que:
    p = que.popleft()
    print('p,que:',p,que)

    for next in ikeru[p]:
        print('next,out:',next,out)
        if out[next]==10**6:
            que.append(next)
            out[next]=p+1


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

Submission status: Runtime Error

Solution code:
import math
from math import gcd
INF = float("inf")

import sys
input=sys.stdin.readline
sys.setrecursionlimit(500*500)
import itertools
from collections import Counter

def main():
    N,M = map(int, input().split())

    L = [[0]*N for _ in range(N)] # n*nの隣接行列の作成
    for _ in range(M): # 隣接行列の作成
        a,b = map(int, input().split())
        L[a-1][b-1] = 1
        L[b-1][a-1] = 1

    d = [0]*N # 訪問スタンプ
    p = [0]*N # パス

    def dfs(x):
        d[x] = 1
        print("a",p)
        for v in range(N):
            if L[x][v] == 0:
                continue
            if p[v] == 0 and d[v] == 0:
                p[v] = x+1
                print(p)
            elif p[v] != x and d[v]==0:
                print("No")
                exit()
            if d[v] == 0:
                dfs(v)

    for u in range(N):
        if d[u] == 0:
            dfs(u)
    print(p)


if __name__=="__main__":
    main()

Submission status: Runtime Error

Solution code:
def nearlist(N, LIST):
    NEAR = [set() for _ in range(N)]
    for a, b in LIST:
        NEAR[a - 1].add(b - 1)
        NEAR[b - 1].add(a - 1)
    return NEAR


def dfs(NEAR, S, N):  # 深優先探索  # スタック
    dist = [n for _ in range(N)]  # 前処理
    PATH = [-1 for _ in range(N)]
    dist[S], PATH[S] = 0, 's'
    stack, frag = [S], set([S])

    while len(stack) > 0:
        q = stack.pop()
        for i in NEAR[q]:  # 移動先の候補
            if i != 0 and i in frag:
                dist[i] = dist[PATH[i]] + 1
            if dist[i] > dist[q] + 1:
                dist[i] = dist[q] + 1
                PATH[i] = q
            if i in frag:  # 処理済みか否か
                continue
            stack.append(i), frag.add(i)
        print(dist,PATH)
    return PATH


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

near = nearlist(n, ab)
path = dfs(near, 0, n)

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

Submission status: Runtime Error

Solution code:
def nearlist(N, LIST):
    NEAR = [set() for _ in range(N)]
    for a, b in LIST:
        NEAR[a - 1].add(b - 1)
        NEAR[b - 1].add(a - 1)
    return NEAR


def dfs(NEAR, S, N):  # 深優先探索  # スタック
    dist = [n for _ in range(N)]  # 前処理
    PATH = [-1 for _ in range(N)]
    dist[S], PATH[S] = 0, 's'
    stack, frag = [S], set([S])

    while len(stack) > 0:
        q = stack.pop()
        for i in NEAR[q]:  # 移動先の候補
            dist[i] = dist[PATH[i]] + 1
            if dist[i] > dist[q] + 1:
                dist[i] = dist[q] + 1
                PATH[i] = q
            if i in frag:  # 処理済みか否か
                continue
            stack.append(i), frag.add(i)
    return PATH


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

near = nearlist(n, ab)
path = dfs(near, 0, n)

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

Submission status: Runtime Error

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

P = {}
A = []
B = []

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

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

for a, b in zip(A, B):
    P[b].append(a)
    P[a].append(b)

ans = [0] * (N + 1)
ans[1] = 1

def search(numbers):
    next_numbers = []
    for number in numbers:
        for x in P[number]:
            if ans[x] == 0:
                ans[x] = number
                next_numbers.append(x)
    if next_numbers:
        search(next_numbers)

search([1])

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