Problem:


Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 2 \times 10^5

1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.



Sample input:
4 4
1 2
2 3
3 4
4 2


Sample output:
Yes
1
2
2

Submission status: Wrong Answer

Solution code:
import heapq
import sys

input = sys.stdin.readline

def dijkstra_heap(s,edge,n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

def main():
    N, M = map(int, input().split())
    edge = [[] for i in range(N)]
    for i in range(M):
        A, B = map(int, input().split())
        A -= 1
        B -= 1
        edge[A].append([1,B])
        edge[B].append([1,A])
    d = dijkstra_heap(0,edge,N)

    for i in range(N):
        if d[i] == float('inf'):
            print('No')
            exit()
    print('Yes')
    for i in range(1,N):
        print(d[i])



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N , M =[int(hoge) for hoge in input().split()]
route = [[] for i in range(N)]
for i in range(M):
    A,B = [int(hoge)-1 for hoge in input().split()]
    route[A].append(B)
    route[B].append(A)
#全域部分木をほどよく作れるかどうか

#BFS
queue = deque()#append,popleft
went = [-1] * N
went[0] = True
queue.append(0)
while queue:
    cur = queue.popleft()
    for togo in route[cur]:
        if went[togo] == -1:
            went[togo] = cur
            queue.append(togo)

if any([x == -1 for x in went]):
    print("No")
else:
    for w in went[1:]:
        print(w+1)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict,deque
n,m = map(int,input().strip().split())
graph = defaultdict(list)
for _ in range(m):
    u,v = map(int,input().strip().split())
    graph[u].append(v)
    graph[v].append(u)

queue = deque()
queue.append(1)

mini_passage = [1,1]+[float('inf')]*(n)
visited = [False]*(n+1)
level = 0
while queue:
    #print(queue,mini_passage,level)
    temp = []
    while queue:
        x = queue.pop()
        mini_passage[x] = min(mini_passage[x],level)
        visited[x] = True
        for neighbour in graph[x]:
            if not visited[neighbour]:
                temp.append(neighbour)
    queue = temp.copy()
    level += 1

ans = []
f = 0
for val in mini_passage[2:]:
    if val==float('inf'):
        f = 1
        break
    ans.append(val)
if f:
    print("Yes")
    for val in ans:
        print(val)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
class queue:
    listQ = []
    def push(self, x):
        self.listQ.append(x)
    def pop(self):
        a = self.listQ[0]
        del self.listQ[0]
        return a
    def length(self):
        return len(self.listQ)


n, m = map(int, input().split())
nodeMap = {}
doneL = [0]*(n+1)
doneL[1] = -1
for i in range(m):
    a, b = map(int, input().split())
    if a in nodeMap:
        nodeMap[a].append(b)
    else:
        nodeMap[a] = [b]
    if b in nodeMap:
        nodeMap[b].append(a)
    else:
        nodeMap[b] = [a]

q = queue()
q.push(1)
while q.length():
    poped = q.pop()
    popedL = nodeMap[poped]
    for r in popedL:
        print(r)
        if doneL[r] != 0:
            pass
        else:
            doneL[r] = poped
            q.push(r)
print("Yes")
for r in doneL:
    if r <= 0:
        pass
    else:
        print(r)

Submission status: Wrong Answer

Solution code:

n,m = map(int,input().split())
from collections import defaultdict
G = defaultdict(list)
for _ in range(m):
    a,b = map(int,input().split())
    G[a-1].append(b-1)
    G[b-1].append(a-1)


# G[v]: 頂点vに隣接する頂点list
# N: 頂点数

from collections import deque
dist = [-1]*n
que = deque([0])
dist[0] = 0
while que:
    v = que.popleft()
    d = dist[v]
    for w in G[v]:
        if dist[w] > -1:
            continue
        dist[w] = d + 1
        que.append(w)

if -1 in dist:
    print("No")
    exit()
else:
    print("Yes")
    for d in dist[1:]:
        print(d)

Submission status: Wrong Answer

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

for a,b in lis:
    path[a-1].append(b-1)
    path[b-1].append(a-1)
gone = [0] * n
gone[0] = 1
ans = [-1] * n
now = {0}
while now:
    a = now.pop()
    for go in path[a]:
        if gone[go] == 0:
            gone[go] = 1
            ans[go] = a
            now.add(go)
print("Yes")
for num in ans:
    if num != -1:
        print(num+1)

Submission status: Wrong Answer

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

N, M = map(int, readline().split())
AB = [list(map(int, readline().split())) for i in range(M)]
AB = [(a-1, b-1) for a,b in AB]

adj = [[] for i in range(N)]
for a,b in AB:
    adj[a].append(b)
    adj[b].append(a)

ans = [-1] * N

q = deque()
q.append(0)

while q:
    n = q.popleft()
    for c in adj[n]:
        if ans[c] == -1:
            ans[c] = n
            q.append(c)

if all(v != -1 for v in ans[1:]):
    print('YES')
    for c in ans[1:]:
        print(c + 1)
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
import queue
from collections import defaultdict
n,m = map(int,input().split())
g = defaultdict(set)
ans = [0]*n
for _ in range(m):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    g[a].add(b)
    g[b].add(a)

visited = [False]*n
visited[0] = True
q = queue.Queue()
q.put(0)
while not q.empty():
    v = q.get()
    for p in g[v]:
        if not visited[p]:
            ans[p] = v
            q.put(p)
            visited[p] = True
for x in ans[1:]:
    print(x+1)

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
E = [[] for _ in range(N)]
for _ in range(M):
  A, B = map(int, input().split())
  E[A-1] += [B-1]
  E[B-1] += [A-1]

ans = [-1]*N
T = [0]
while len(T)>0:
  P = T
  T = []
  for x in P:
    for e in E[x]:
      if ans[e]==-1:
        T += [e]
        ans[e] = x
for a in ans[1:]:
  print(a+1)

Submission status: Wrong Answer

Solution code:
import os

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

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

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, M = list(map(int, sys.stdin.buffer.readline().split()))
A, B = list(zip(*[map(int, sys.stdin.buffer.readline().split()) for _ in range(M)]))

graph = csr_matrix((np.ones(M), (A, B)), shape=(N + 1, N + 1))
_, pred = dijkstra(graph, directed=False, indices=(1,), return_predecessors=True)
ans = pred[0][2:]
print('Yes')
print(*ans, sep='\n')

Submission status: Wrong Answer

Solution code:
import queue
import sys

input = sys.stdin.readline

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

parent = [-1] * (N)
parent[0] = 0

q = queue.Queue()
q.put(0)
while not q.empty():
    pos = q.get()
    for next_room in path[pos]:
        if parent[next_room] == -1:
            q.put(next_room)
        else:
            parent[pos] = next_room

if -1 in parent:
    print("No")
else:
    print("Yes")
    for elem in parent[1:]:
        print(elem + 1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

n,m,*ab = map(int,open(0).read().split())

a = ab[::2]
b = ab[1::2]

L = csr_matrix(([1]*m,(a,b)),shape=(n+1,n+1))
               
_, route = dijkstra(L ,directed = False, indices = 1, return_predecessors = True)

if (route[2:]>0).all():
    print("Yes")
    print("\n".join(map(str,route[2:])))
else:
    print("No")

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
import bisect
from collections import deque
from fractions import gcd
from functools import lru_cache


#############
# Constants #
#############

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

#############
# Functions #
#############

######INPUT######
def inputI(): return int(input().strip())
def inputS(): return input().strip()
def inputIL(): return list(map(int,input().split()))
def inputSL(): return list(map(str,input().split()))
def inputILs(n): return list(int(input()) for _ in range(n))
def inputSLs(n): return list(input().strip() for _ in range(n))
def inputILL(n): return [list(map(int, input().split())) for _ in range(n)]
def inputSLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def Yes(): print("Yes"); return
def No(): print("No"); return

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])
    return arr

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#############
# Main Code #
#############

N,M = inputIL()

graph = [[] for i in range(N)]
for _ in range(M):
  a,b = inputIL()
  graph[a-1].append(b-1)
  graph[b-1].append(a-1)
  
d = [INF for i in range(N)]
prev = [None for i in range(N)]
q = deque([0])
d[0] = 0
while q:
  x = q.popleft()
  nd = d[x]+1
  for nx in graph[x]:
    if nd < d[nx]:
      d[nx] = nd
      prev[nx] = x
      q.append(nx)
      
for i in prev[1:]:
  print(i+1)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N,M=MI()
    adj=[[]for _ in range(N)]
    
    for i in range(M):
        a,b=MI()
        a-=1
        b-=1
        adj[a].append(b)
        adj[b].append(a)
        
    import queue
    q=queue.Queue()
    q.put((0,-1))
    ans=[-1]*N
    
    while not q.empty():
        v,p=q.get()
        for nv in adj[v]:
            if nv!=p:
                if ans[nv]==-1:
                    q.put((nv,v))
                    ans[nv]=v
                    
    for i in range(1,N):
        print(ans[i]+1)
                

main()

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, m = mi()
    adj = [[] for _ in range(n)]
    for _ in range(m):
        a, b = mi_0()
        adj[a].append(b)
        adj[b].append(a)
    
    visited = [None] * n
    def bfs_queue_traverse(u):
        queue = deque([])
        queue.append((u, 0))
        while queue:
            current, dist = queue.popleft()
            if visited[current] is None:
                visited[current] = dist
                for v in adj[current]:
                    if visited[v] is None:
                        queue.append((v, dist+1))
    bfs_queue_traverse(0)
    print(visited)
    print('Yes')
    for u in range(1, n):
        min_ind, minimum_dist = None, inf
        for v in adj[u]:
            if visited[v] < minimum_dist:
                min_ind, minimum_dist = v, visited[v]
        print(min_ind + 1)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

from collections import defaultdict, deque
g = defaultdict(list)
for a, b in ab:
    g[a - 1].append(b - 1)
    g[b - 1].append(a - 1)

visited = [0] * n
prev = [float('inf')] * n

q = deque([0])
visited[0] = 1

while q:
    cur = q.pop()
    for target in g[cur]:
        if visited[target] == 0:
            visited[target] = 1
            q.append(target)
            prev[target] = cur

f = True
prev2 = []
for i in range(1, n):
    if prev[i] == float('inf'):
        f = False
    prev2.append(prev[i] + 1)

if f:
    print('Yes')
    for p in prev2:
        print(p)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from collections import deque


def main():
    n, m = map(int, input().split())
    g = [[] for _ in range(n)]
    for _ in range(m):
        a, b = map(lambda x: int(x) - 1, input().split())
        g[a].append(b)
        g[b].append(a)
    dist = [-1 for _ in range(n)]
    prev = [-1 for _ in range(n)]
    dist[0] = 0
    q = deque([0])
    while q:
        now = q.pop()
        for next in g[now]:
            if prev[next] < 0:
                prev[next] = now + 1
                dist[next] = dist[now] + 1
                q.append(next)
    if all(prev[i] > 0 for i in range(1, n)):
        print("Yes")
        for i in range(1, n):
            print(prev[i])
    else:
        print("No")


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappop,heappush
N,M = map(int,input().split())
T = [[] for i in range(N)]
for i in range(M):
    a,b = map(lambda x:int(x)-1,input().split())
    T[a].append(b)
    T[b].append(a)

INF = float("inf")
D = [INF]*N
Q = [[0,0]]
while Q:
    d,v = heappop(Q)
    if d >= D[v]:continue
    D[v] = d
    d += 1
    for c in T[v]:
        heappush(Q,[d,c])
if INF in D:
    print("No")
else:
    print("Yes")
    for i in range(1,N):
        print(D[i])

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read


n,m,*ab = [int(i) for i in read().split()]

dist = [-1]*n
dist[0] = 0
ans = [-1]*n

g = [[] for _ in range(n)]
M = iter(ab)
for a,b in zip(M,M):
    g[a-1].append(b-1)
    g[b-1].append(a-1)

q = [0]
while q:
    v = q.pop()
    for c in g[v]:
        if dist[c] >= 0: continue
        dist[c] = dist[v]+1
        ans[c] = v+1
        q.append(c)
    


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

Submission status: Wrong Answer

Solution code:

import sys
sys.setrecursionlimit(10**7)


def inpl():
    return list(map(int, input().split()))


N, M = inpl()

lines = [[] for _ in range(N)]
for _ in range(M):
    a, b = inpl()
    a -= 1
    b -= 1
    lines[a].append(b)
    lines[b].append(a)


ans = [-1] * N


def dfs(s, b):
    global ans

    if ans[s] != -1:
        return
    else:
        ans[s] = b
        for t in lines[s]:
            dfs(t, s)


dfs(0, 0)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque, defaultdict, Counter
from itertools import accumulate, product, permutations, combinations
from operator import itemgetter
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush
from math import ceil, floor, sqrt, gcd, inf
from copy import deepcopy
import numpy as np
import scipy as sp

INF = inf
MOD = 1000000007

n, m = [int(i) for i in input().split()]
A = [[int(i) for i in input().split()]for j in range(m)]    # nは行数

tmp = [[] for i in range(n + 1)]
tmp_2 = [inf for i in range(n + 1)]
res = [0 for i in range(n + 1)]
tmp_2[0] = 0
tmp_2[1] = 0

for a, b in A:
    tmp[a].append(b)
    tmp[b].append(a)
q = deque([1])
while q:
    i = q.popleft()
    for j in tmp[i]:
        if tmp_2[i] + 1 <= tmp_2[j]:
            tmp_2[j] = tmp_2[i] + 1
            q.append(j)
if max(tmp_2) == inf:
    res = "No"
else:
    for a, b in A:
        if tmp_2[a] + 1 == tmp_2[b]:
            res[b] = a
        elif tmp_2[b] + 1 == tmp_2[a]:
            res[a] = b
    res = "Yes\n" + "\n".join([str(r) for r in res[2:]])

print(res)

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
#from operator import itemgetter
#from heapq import heappush, heappop
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
#from scipy.sparse import csr_matrix
#from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
import sys

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

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

N, M = na()
g = [[0] * N for _ in range(N)]
for i in range(M):
    A, B = na()
    A -= 1
    B -= 1
    g[A][B] = 1
    g[B][A] = 1
g = np.array(g)
d, root = shortest_path(g, return_predecessors=True, indices=[0])
#print(d, root)
if 0 not in d[0][1:]:
    print('Yes')
    for i in range(1, N):
        print(root[0][i] + 1)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def show_2d_array(array):
    [print(a) for a in array]


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

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


# show_2d_array(cave)


def bfs(tree, p):
    seen = [False] * len(tree)
    queue = deque((p,))
    depth = [0] * N
    depth[p] = 0
    current_depth = depth[p]
    while len(queue) > 0:
        # print(queue)
        q = queue.popleft()
        seen[q] = True
        # print(q)
        for v in tree[q]:
            if not seen[v]:
                depth[v] = depth[q] + 1
                queue.append(v)
                seen[v] = True


    return depth


depth = bfs(cave, 0)

# print("depth", depth)

sign = [0] * N

ans = "Yes"
for i in range(1, N):
    current = i
    found = False
    while not found:
        next = -1
        for j in cave[current]:
            if depth[j] == depth[current]-1:
                if sign[current] <= 0:
                    next = j
                    sign[current] = next
                    break
                else:
                    next = sign[current]
                    break
        if next < 0:
            ans = "No"
            break

        current = next
        if current == 0:
            found = True

print(ans)
if ans == "Yes":
    [print(s+1) for s in sign[1:]]

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

N, M = map(int, input().split())
path = defaultdict(list)

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

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

while True:
    if len(dst) == 0:break
    tmp = []
    for d in dst:
        for a in path[d]:
            if ans[a] == 0:
                ans[a] = d
                for b in path[a]:
                    if ans[b] == 0:
                        tmp.append(a)

    dst = tmp

for a in ans[2:]:
    if a == 0:
        print('No')
        exit()

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

Submission status: Time Limit Exceeded

Solution code:
import math, sys
N , M = list(map(int, input().split()))

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


i = 1
j = 1
d = 0
#ans = [-1 for _ in range(N)]
cand = []
used = [False for i in range(N)]
dis = [math.inf for i in range(N)]
ans = [-1 for i in range(N)]
tar = 0
cnt = 1
print("Yes")
p = 0

cand = [0]
while len(cand)>0:
    tar = cand.pop(0)
    for each in Es[tar]:
        if not used[each]:
            cand.append(each)
            ans[each]=tar+1
            used[each]= True
for i in range(1,N):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import math, sys
N , M = list(map(int, input().split()))

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


i = 1
j = 1
dis = 0
#ans = [-1 for _ in range(N)]
cand = []
used = [-1 for i in range(N)]
used[0] = 0
tar = 0
cnt = 1
print("Yes")
p = 0
while True:
    for each in Es[tar]:
        if used[each] <0 :
            used[each] = tar
            cand.append(each)
            cnt += 1
    if len(cand) == 0:
        break
    if cnt == N:
        break
    tar = cand.pop(0)

for i in range(1,N):
    print(used[i]+1)

Submission status: Time Limit Exceeded

Solution code:
import math, sys
N , M = list(map(int, input().split()))

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


i = 1
j = 1
dis = 0
ans = [-1 for _ in range(N)]
cand = []
used = [False for i in range(N)]
used[0] = True
tar = 0
cnt = 1
while True:
    for each in Es[tar]:
        if not used[each]:
            used[each]= True
            ans[each] = tar
            cand.append(each)
            cnt += 1
    if len(cand) == 0:
        break
    if cnt == N:
        break
    tar = cand.pop(0)

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

Submission status: Time Limit Exceeded

Solution code:
import math, sys
N , M = list(map(int, input().split()))

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


i = 1
j = 1
dis = 0
ans = [-1 for _ in range(N)]
cand = []
used = [False for i in range(N)]
used[0] = True
tar = 0

while True:
    for each in Es[tar]:
        if not used[each]:
            used[each]= True
            ans[each] = tar
            cand.append(each)
    if len(cand) == 0:
        break
    else:
        tar = cand.pop(0)

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m = map(int,input().split())
li = [list(map(int,input().split())) for _ in range(m)]
g = [[] for _ in range(n)]
l = [0 for _ in range(n)]
seen = [0 for _ in range(n)]

for x,y in li:
    x -= 1
    y -= 1
    g[x].append(y)
    g[y].append(x)

def bfs():
    que = deque([])
    l[0] = 0
    seen[0] = 1
    for i in g[0]: 
        que.append((i,0))
    while que:
        a,b = que.popleft()
        seen[a] = 1
        if not l[a]:l[a] = b+1
        for i in g[a]:
            if i != b and not l[i]:
                
                que.append((i,a))

bfs()
if all(seen):
    print('Yes')
    for i in l[1:]:
        print(i)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m = map(int,input().split())
g = [[] for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)
    
def bfs(u):
    queue = deque([u])
    d = [None]*n    
    d[u] = 0
    while queue:
        v=queue.popleft()
        for i in g[v]:
            if d[i] is None:
                p[i] = v
                queue.append(i)
    return d

p = [None]*n
d = bfs(0)
print('Yes')
        
for q in range(1,n):
    print(int(p[q])+1)

Submission status: Time Limit Exceeded

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

list1 = [-1] * (N + 1)
list2 = [[] for _ in range(N + 1)]
list3 = [-1] * (N + 1)

for _ in range(M):
    a, b = map(int, input().split())
    list2[a].append(b)
    list2[b].append(a)
    s = min(a, b)
    l = max(a, b)
    while list1[s] > 0:
        s = list1[s]
    while list1[l] > 0:
        l = list1[l]
    if s == l:
        continue
    s, l = min(s, l), max(s, l)
    list1[s] += list1[l]
    list1[l] = s

if list1[1] != - N:
    print("No")
else:
    print("Yes")
    list3[1] = 0
    que = list(set(list2[1]))
    count = 1
    while len(que) > 0:
        for i in range(len(que)):
            a = que.pop(0)
            if list3[a] < 0:
                que += list2[a]
                list3[a] = count
        count += 1

    for i in range(2, N + 1):
        for j in list2[i]:
            if list3[i] - 1 == list3[j]:
                print(j)
                break

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
n,m=map(int,input().split())
root=[[] for i in range(n+1)]
for i in range(m):
    a,b=map(int,input().split())
    root[a].append(b)
    root[b].append(a)
dep=[-1]*(n+1)
sign=[0]*(n+1)
dep[0]=0
dep[1]=0
def search(x):
    for i in root[x]:
        if dep[i]==-1:
            dep[i]=dep[x]+1
            sign[i]=x
            search(i)
        elif dep[i]>dep[x]+1:
            dep[i]=dep[x]+1
            sign[i]=x
            search(i)
search(1)
print("Yes")
for i in range(2,n+1):
    print(sign[i])