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: Time Limit Exceeded

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

root = {}
for i in range(M):
  A, B = list(map(int, input().strip().split()))
  if A not in root:
    root[A] = set()
  root[A].add(B)  
  if B not in root:
    root[B] = set()
  root[B].add(A)
    
#print(root)

if 1 not in root or len(root) != N:
  print('No')
else:
  A = {}
  A[1] = 0
  current = 1
  while True:
    #print(f'{current=}')
    #print(A)
    for r in root[current]:
      if r not in A:
        A[r] = current
    current = r
    if len(A) == N:
      break

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

Submission status: Time Limit Exceeded

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

A = []
B = []

for x in range(M):
    At,Bt = map(int,input().split())
    A.append(At)
    B.append(Bt)
rinsetu =[[0 for x in range(N)] for y in range(N)]
for x in range(M):
    rinsetu[A[x]-1][B[x]-1] = 1
    rinsetu[B[x]-1][A[x]-1] = 1
L = csr_matrix(rinsetu)
shortest,p =  shortest_path(L,return_predecessors=True)
ans =[]
for x in p[0]:
    if x == -9999:
        pass
    else:
        ans.append(x+1)
print("Yes")
for x in ans:
    print(x)

Submission status: Time Limit Exceeded

Solution code:
#from collections import deque
#import sys
#sys.setrecursionlimit(10**6)
#input = sys.stdin.buffer.readline
n,m=map(int,input().split())
g = [[] for j 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)
q = [(0,-1)]
d=[-1]*n
d[0]=0
res={}
while len(q)>0:
    u,r = q.pop(0)
    for v in g[u]:
        if d[v] == -1 and r != v:
            d[v] = d[u] + 1
            q.append((v,u))
            if not v-1 in res:
                res[v-1] = u+1
res = sorted(res.items())
if len(res) != n-1:
    print("No")
    exit()
print("Yes")
for i,j in res:
    print(j)

Submission status: Time Limit Exceeded

Solution code:
import sys
import  math
from heapq import *
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

    
N,M=nm()
INF=10**18
def bfs(start,edge):
    d=[INF]*(N+1)
    ans=[0]*(N+1)
    d[start]=0
    q=[(0,start)]
    while(len(q)!=0):
        ci,i=heappop(q)
        for j in edge[i]:
            if(d[j]>=d[i]+1):
                d[j]=d[i]+1
                heappush(q,(d[j],j))
                ans[j]=i

    return ans




edge=[[]for _ in range(N+1)]
for i in range(M):
    A,B=nm()
    edge[A].append(B)
    edge[B].append(A)

ans=bfs(1,edge)

for i in range(2,N+1):
    if(ans[i]==0):
        print('No')
        sys.exit(0)

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

Submission status: Time Limit Exceeded

Solution code:
# Code for D - .. (Double Dots)
# Use input() to fetch data from STDIN
from collections import defaultdict

[n, m] = map(int, input().split())
a = [0 for x in range(m)]
b = [0 for x in range(m)]

path = defaultdict(lambda: [])

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


print("Yes")

mem = [0 for x in range(n + 1)]
q = [1]
while len(q) > 0:
    base = q.pop(0)
    rooms = path[base]

    rs = list(filter(lambda r: mem[r] == 0, rooms))
    q = q + rs
    for r in rs:
        mem[r] = base

for x in mem[2:]:
    print(x)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
from collections import deque
import collections
import heapq
# import time

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

for i in range(m):
    # a[i], b[i] = list(map(int, input().split()))
    a, b = list(map(int, input().split()))
    path[a].append(b)
    path[b].append(a)
# start = time.time()
# 部屋1から出発して、
ans = [0]*(n+1)
visited = [1]
que = deque([[1, 1]])  # 今の場所、前の場所
que_items = [1]
now = 1
prev = 1
# BFS
while len(que) > 0:
    now, prev = que.popleft()
    # print('pop', now)
    for can_go in path[now]:
        if(not (can_go in visited or can_go in que_items)):
            # print('push', can_go)
            que.append([can_go, now])
            que_items.append(can_go)
    if (now in visited):
        continue
    ans[now] = prev
    visited.append(now)

if (len(visited) != n):
    print('No')
else:
    print('Yes')
    for _ans in ans[2:]:
        print(_ans)

# print(time.time() - start)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    import collections
    n, m = map(int, input().split())
    hw = [[0]*(n+1) for _ in range(n+1)]
    for i in range(m):
        a, b = map(int, input().split())
        hw[a][b] = 1
        hw[b][a] = 1
    dis = [0] * (n+1)
    arr = [-1] * (n+1)
    que = collections.deque([1])
    while len(que) != 0:
        a = que.popleft()
        test = hw[a]
        for i in range(len(test)):
            if test[i] == 1:
                if arr[i] == -1:
                    arr[i] = a
                    que.append(i)
    if 0 in arr[2:]:
        print("No")
    else:
        print("Yes")
        for i in range(2, len(arr)):
            print(arr[i])
 
resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]

n, m = map(int, input().split())
g = Graph()
for i in range(m):
    a, b = map(int, input().split())
    g.add_edge(a-1, b-1, 1)
    g.add_edge(b-1, a-1, 1)

d = Dijkstra(g, 0)
A = []
for i in range(n):
    a = d.shortest_distance(i)
    if a == float('inf'):
        print("No")
        break
    else:
        A.append(d.shortest_distance(i))

if len(A) == n:
    ANS = [0] * n
    for i in range(1, n):
        if ANS[i] == 0:
            B = d.shortest_path(i)
            for j in range(A[i]):
                ANS[B[-1-j]] = B[-1-j-1]+1
    # print(ANS)
    print("Yes")
    for i in ANS[1:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

sys.setrecursionlimit(100000000)

def yn(b):
    print("Yes" if b==1 else "No")
    return

def xxx(t,memo,ans,kyori):
    for a in memo[t]:
        if ans[a] == -1 or kyori[a] > (kyori[t]+1):
            ans[a]=t
            kyori[a]=kyori[t]+1
            xxx(a,memo,ans,kyori)


def resolve():
    readline=sys.stdin.readline

    n,m=map(int, readline().rstrip().split())
    memo=[[] for i in range(n)]
    ans=[-1]*n
    kyori=[-1]*n
    ans[0]=0
    kyori[0]=0
    for i in range(m):
        a,b=map(int, readline().rstrip().split())
        memo[a-1].append(b-1)
        memo[b-1].append(a-1)
    xxx(0,memo,ans,kyori)
    #tt=[0]
    #nx=[]
    #for t in tt:
    #    for a in memo[t]:
    #        if ans[a]
        
    #memo

    if -1 in ans:
        print("No")
    else:
        print("Yes")
        for i in range(1,n):
            print(ans[i]+1)


    #arr=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Time Limit Exceeded

Solution code:

import numpy as np

s = 1  # 始点ノード番号


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

link = []
for i in range(M):
    array = list(map(int, input().strip().split()))
    link.append(array)

E = np.array(link)
E_inv = E[:, ::-1]
E = np.concatenate([E, E_inv])

def Dijkstra(s):

    # 配列などの用意
    D = np.full(N, float('inf')) #  D[x]：始点sからxまでの最短経路長
    visited = np.zeros(N, dtype=np.bool) # visited[x]：頂点xを既に訪問したか否か(最短経路が確定したか否か)
    previous = np.full(N, -1) # previous[x]：始点sからxへの最短経路におけるxの直前にいた頂点
    S = [] # 集合S：着目頂点に対する隣接頂点のうち最短路がまだ確定していない点の集合

    # 初期化
    S.append(s)
    D[s-1] = 0 # 始点についてD[]=0

    while(len(S) != 0): # Sが空でない間
        w = S[np.argmin(D[[i-1 for i in S]])] # Sの中でD[w](sからのパス長)が最も小さい頂点wに訪問
        S.remove(w) # Sからwを削除
        visited[w-1] = True # wまでの最短路が確定，wは訪問済みとする

        X = E[np.where(E[:, 0] == w)][:,1].astype(int) # wに対する隣接点集合X
        X = [i for i in X if visited[i-1] != True] # wに対する隣接点のうち未訪問のすべての頂点集合X
        for x in X: # X内の各要素(頂点)xについて
            new_dist = D[w-1] + 1
            if D[x-1] > new_dist:
                D[x-1] = new_dist
                previous[x-1] = w
                S.append(x)
                set(S)

        previous[0] = 0
    return D, previous

D, previous = Dijkstra(1)


if -1 in previous:
    print("No")
else:
    print("Yes")
    for i in range(1, N):
        print(previous[i])

Submission status: Time Limit Exceeded

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

X=[list(map(int,input().split())) for i in range(M)]
Y=[0 for i in range(N)]
Y[0]=-1
Z=[[] for j in range(N)]

import copy


for i in X:
  Z[i[0]-1].append(i[1]-1)
  Z[i[1]-1].append(i[0]-1)

  
item =[0]
while (0 in Y):
  note=[]
  for i in item:
    note=note+Z[i]
    for j in Z[i]:
      if Y[j]==0:
        Y[j]=i+1
  item=copy.deepcopy(note)
print("Yes")
for i in Y:
  if i==-1:
    continue
  print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
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)
visited = [-1] * n
ans = [-1] * n
queue = deque([0])
while queue:
    pos = queue.popleft()
    visited[pos] = 1
    if len(path[pos]) > 0:
        l = path[pos]
        for i in range(len(l)):
            if visited[l[i]] == -1:
                if ans[l[i]] == -1:
                    ans[l[i]] = pos + 1
                queue.append(l[i])
print("Yes")
for i in range(1, n):
    print(ans[i])

Submission status: Time Limit Exceeded

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

l = [[False for _ in range(n)] for __ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    l[a-1][b-1] = l[b-1][a-1] = True

p = [0 for _ in range(n)]
s = [1]
sd = []
while len(s) != 0:
    r = s.pop(0)
    sd.append(r)
    for i, b in enumerate(l[r-1]):
        if b:
            if i+1 not in sd:
                if p[i] == 0:
                    p[i] = r
                if i+i not in s:
                    s.append(i+1)

if 0 in p[1:]:
    print('No')
else:
    print('Yes')
    for pp in p[1:]:
        print(pp)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path


def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]


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

ll = np.array([[0 for _ in range(N)] for _ in range(N)])
for path in paths:
    u, v = path
    ll[v - 1][u - 1] = 1
    ll[u - 1][v - 1] = 1

csr = csr_matrix(ll)

d, p = shortest_path(csr, method="D", indices=0, return_predecessors=True, unweighted=True, directed=False)
if np.inf in d:
    print("No")
else:
    print("Yes")
    for i in p[1:]:
        print(i + 1)

Submission status: Time Limit Exceeded

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

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

s=[n+1 for i in range(0,n+1)]
ans=[n+1 for i in range(0,n+1)]
s[1]=0


while(a!=[]):
    
    i=a[0]
    j=b[0]
    x=s[a[0]]
    y=s[b[0]]
    a.pop(0)
    b.pop(0)
    if (x==n+1 and y==n+1):
        a.append(i)
        b.append(j)

    elif (x>y):
        s[i]=s[j]+1
        ans[i]=j
    elif (y>x):
        s[j]=s[i]+1
        ans[j]=i

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

Submission status: Time Limit Exceeded

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

AB = [[] for _ in range(N+1)]
ans = [-1] * (N+1)

for _ in range(M):
    A, B = list(map(int, input().split()))
    AB[A].append(B)
    AB[B].append(A)

new_places = [1]
max_N = N + 1

def check(targets, waras):
    for target in targets:
        if target in waras:
            return target
    return None

while new_places:
    tmp_places = []
    for i in range(2, max_N):
        if ans[i] == -1:
            check_ans =  check(new_places, AB[i])
            if check_ans:
                ans[i] = check_ans
                tmp_places.append(i)
    new_places = tmp_places

if all(i != -1 for i in ans[2:]):
    print("Yes")
    for i in ans[2:]:
        print(i)

else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import itertools as iter
import math as m
from collections import deque

def main():
    N, M = list(map(int, input().split()))
    R = []
    for _ in range(M):
        R.append(list(map(int, input().split())))
    
    q = deque()
    s = set()
    r = [0] * (N+1)
    q.append(1)
    while any(q):
        x = q.popleft()
        s.add(x)
        ro = R[:]
        for i in ro:
            if i[0] == x and i[1] not in s and i[1] not in q:
                if r[i[1]] == 0:
                    r[i[1]] = i[0]
                q.append(i[1])
                R.remove(i)
            elif i[1] == x and i[0] not in s and i[0] not in q:
                if r[i[0]] == 0:
                    r[i[0]] = i[1]
                q.append(i[0])
                R.remove(i)
    if len(s) == N:
        print("Yes")
        for i in r[2:]:
            print(i)
    else:
        print("No")
    
        

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N , M = map(int , input().split())
A = [ 0 for i in range(M)]
B = [ 0 for i in range(M)]
for i in range(M):
  A[i] , B[i] = map(int , input().split())

direction = [N for i in range(N)]
point = [N for i in range(N)]
for i in range(M):
  if A[i] == 1:
    direction[B[i] - 1] = 1
    point[B[i] - 1] = 1
  if B[i] == 1:
    direction[A[i] - 1] = 1
    point[A[i] - 1] = 1
step = 1
k=1
while k != 0:
  k = 0

  for i in range(M):
    a = point[A[i] - 1]
    b = point[B[i] - 1]
    m = min([a, b])
    if m == step and a != b:
      if a == m:
        direction[B[i] - 1] = A[i]
        point[B[i] - 1] = m+1
      if b == m:
        direction[A[i] - 1] = B[i]
        point[A[i] - 1] = m+1
      k += 1

  step += 1
print('Yes')
for i in range(N - 1):
  print(str(direction[i + 1]))

Submission status: Time Limit Exceeded

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

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

n, m = map(int, input().split())
data = []
row = []
col = []
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    data.append(1)
    row.append(a)
    col.append(b)
    data.append(1)
    row.append(b)
    col.append(a)
graph = csr_matrix((data, (row, col)), shape=(n, n))
_, p = shortest_path(graph, return_predecessors=True, directed=False, unweighted=True, indices=0)
for item in p[1:]:
    if(item < 0):
        print("No")
        exit()
print("Yes")
for item in p[1:]:
    print(item + 1)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
edge = {i: [] for i in range(1, n+1)}
reached = {i: 0 for i in range(2, n+1)}
guide = {i: 0 for i in range(2, n+1)}
for _ in range(m):
    a, b = map(int, input().split())
    edge[a].append(b)
    edge[b].append(a)

# print(edge)
queue = [(e, 1) for e in edge[1]]
while len(queue) > 0:
    # print(queue)
    e, now = queue.pop(0)
    if reached[e] == 0:
        reached[e] = 1
        guide[e] = now
        for next in edge[e]:
            if next != 1 and reached[next] == 0:
                queue.append((next, e))

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

Submission status: Time Limit Exceeded

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

answer = [0]*N
answer[0] = 1

counter = [1000000]*N
counter[0] = 0

grph = []
for i in range(0,M):
    grph.append(list(map(int,input().split())))

for j in range(N):
    for i in range(len(grph)):
        if answer[grph[i][0]-1] != 0 and counter[grph[i][0]-1]+1<counter[grph[i][1]-1]:
            answer[grph[i][1]-1] = grph[i][0]
            counter[grph[i][1] - 1] = counter[grph[i][0]-1]+1
        elif answer[grph[i][1]-1] != 0 and counter[grph[i][1]-1]+1<counter[grph[i][0]-1]:
            answer[grph[i][0]-1] = grph[i][1]
            counter[grph[i][0] - 1] = counter[grph[i][1]-1]+1

if not 0 in answer:
    print('Yes')
    for i in range(1,len(answer)):
        print(answer[i])
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
N,M=list(map(int,input().split()))
road_list=[]
for i in range(M):
  road_list.append(list(map(int,input().split())))
ans_dict=dict([])
before_room=[1]
while True:
  temp_room=[]
  for j in range(len(before_room)):
    temp_delete=[]
    for i in road_list:
      #print(road_list)
      #print("before_room=",before_room,j)
      if i[0]==before_room[j]:
        if i[1] not in ans_dict:
          ans_dict[i[1]]=before_room[j]
          temp_room.append(i[1])
        #road_list.remove(i)
        temp_delete.append(i)
      if i[1]==before_room[j]:
        if i[0] not in ans_dict:
          ans_dict[i[0]]=before_room[j]
          temp_room.append(i[0])
        #road_list.remove(i)
        temp_delete.append(i)
    for temp in temp_delete:
      road_list.remove(temp)
  before_room=temp_room
    #if len(ans_dict)==N-1:
    #  break
  if len(ans_dict)==N-1:
    break
#print(ans_dict)
if len(ans_dict)==N-1:
  print("Yes")
  for i in range(len(ans_dict)):
    print(ans_dict[i+2])
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
import math
from collections import deque
n,m=[int(_) for _ in input().split()]
A=[[int(_) for _ in input().split()] for l in range(m)]
R=deque([] for _ in range(n))
for a in A:
    R[a[0]-1].append(a[1]-1)
    R[a[1]-1].append(a[0]-1)
print("Yes")
for h in range(1,n):
    dq=deque()
    dq.appendleft([h])
    while dq:
        x=dq.popleft()
        if 0 in R[x[-1]]:
            if len(x)==1:
                print(1)
            else:
                print(x[1]+1)
            break
        for a in R[x[-1]]:
            dq.append(x+[a])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n, m = map(int, input().split(" "))
load = {}
for _ in range(m):
    a, b = map(int, input().split(" "))
    load[a] = load.get(a, set()) | set({b})
    load[b] = load.get(b, set()) | set({a})

queue = deque([1])
visited = {1: 1}

while len(queue) != 0:
    curr = queue.popleft()
    for _next in load[curr]:
        if visited.get(_next, -1) == -1:
            visited[_next] = curr
            queue.append(_next)

if len(visited) == n:
    print("Yes")
    for i in range(2, n+1):
        print(visited[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int, input().split())
a_list=[]
for i in range(M):
    a_list.append(list(map(int,input().split())))
V_list=[]
for i in range(1,N+1) :
    i_list=[]
    for item in a_list :
        if item[0]==i :
            i_list.append(item[1])
        elif item[1]==i :
            i_list.append(item[0])
    V_list.append(i_list)

from collections import deque
s_list=[0]*N
current_V=deque()
current_V.append(1)

while (current_V!=deque([])) :
    a=current_V.popleft()
    current_list=V_list[a-1]
    for item in current_list :
        if s_list[item-1]==0 :
            current_V.append(item)
            s_list[item-1] =a
print('Yes')
for item in s_list[1:] :
    print(item)

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
from collections import defaultdict

iim = lambda: map(int, input().rstrip().split())

def resolve():
    N, M = iim()
    it = map(int, sys.stdin.read().split())

    d1 = defaultdict(list)

    for i, j in zip(it, it):
        d1[i].append(j)
        d1[j].append(i)

    ans = [0] * (N+1)
    dq = [1]
    visited = set([1])

    while True:
        dq2 = []
        for i in dq:
            for j in d1[i]:
                if j in visited:
                    continue
                dq2.append(j)
                ans[j] = i
            visited.update(dq2)

        if len(visited) == N:
            break
        elif not dq2:
            break

        dq = dq2

    if len(visited) == N:
        print("Yes", *ans[2:], sep="\n")
    else:
        print("No")





if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

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

miti = [0] * (N - 1)
path = { i:set() for i in range(1, N+1)}
routes = []
for i in range(M):
    Ai, Bi = [ int(i) for i in input().strip().split(' ')]
    path[Ai].add(Bi)
    path[Bi].add(Ai)

targets = [1]
check_list = set()
check_list.add(1)
while True:
    for target in targets:
        targets = []
        check_list.add(target)
        for t in path[target]:
            if miti[t-2] == 0:
                miti[t-2] = target
        targets += path[target]

    if len(check_list) == N:
        break
if min(miti) == 0:
    print('No')
else:
    print('Yes')
    for mt in miti:
        print(mt)

Submission status: Time Limit Exceeded

Solution code:
# from math import factorial,sqrt,ceil #,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from bisect import bisect_left
# from heapq import heappush,heappop
# from numba import njit
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from fractions import gcd

# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
import networkx as nx
G = nx.Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
N,M = map(int,input().split())

G.add_nodes_from(list(range(1,N+1)))
for _ in range(M):
    A,B = map(int,input().split())
    G.add_edge(A, B)

shortestPath = nx.shortest_path(G, target=1)
if len(shortestPath) != N:
    print("No")
    exit()

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

# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from collections import deque
    n, m = map(int, input().split())
    michi=s = [[0 for i in range(n)] for j in range(n)]
    for _ in range(m):
        a, b = map(int, input().split())
        michi[a-1][b-1]=1
        michi[b - 1][a - 1] = 1
    heya=[-1]*n

    def f():
        check=0
        que = deque([])
        que.append(0)
        while que:
            if check==n:
                break
            else:
                p=que.popleft()
                for i in range(n):
                    if michi[p][i]==1 and heya[i]==-1:
                        michi[p][i]=0
                        heya[i]=p+1
                        check+=1
                        que.append(i)
        return

    f()
    print("Yes")
    for i in heya[1:]:
        print(i)
resolve()

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
ans=[0]*n
route={}
for i in range(m):
  a,b=map(int,input().split())
  if a in route:
    li=route[a]
    li.append(b)
    route[a]=li
  else:
    route[a]=[b]
  if b in route:
    li=route[b]
    li.append(a)
    route[b]=li
  else:
    route[b]=[a]
que=[1]
clear=[0]*n
while len(que)>0:
  x=que.pop(0)
  if clear[x-1]==0:
    que.extend(route[x])
    for k in route[x]:
      if ans[k-1]==0:
        ans[k-1]=x
    clear[x-1]=1
ans.pop(0)
if sorted(ans)[0]==0:
  print("No")
else:
  print("Yes")
  for k in ans:
    print(k)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
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)
visited = [-1] * n
ans = [-1] * n
queue = deque([0])
while queue:
    pos = queue.popleft()
    visited[pos] = 1
    if len(path[pos]) > 0:
        l = path[pos]
        for i in range(len(l)):
            if visited[l[i]] == -1:
                if ans[l[i]] == -1:
                    ans[l[i]] = pos + 1
                queue.append(l[i])
print("Yes")
for i in range(1, n):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra


n,w = map(int,input().split()) #n:頂点数　w:辺の数
aint=[]
cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(w):
    x,y = map(int,input().split())
    cost[x-1][y-1] = 1
    cost[y-1][x-1] = 1


distance_mat, processors = dijkstra(cost, directed = False, indices = [0, 1], return_predecessors = True)

p=processors[0]
p=p[1:]

if(-9999 in p):
    print("No")
    exit()
else:
    print("Yes")

for i in p:
    print(i+1)

Submission status: Time Limit Exceeded

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

l= deque([1])
unvisit= [True]*(n+1)
unvisit[1] = False
anslis = [0]*(n+1)
while len(l) != 0:
    now = l.popleft()
    for r in rode:
        if r[0] == now:
            if unvisit[r[1]]:
                unvisit[r[1]] = False
                l.append(r[1])
                anslis[r[1]] = now
        if r[1] == now:
            if unvisit[r[0]]:
                unvisit[r[0]] = False
                l.append(r[0])
                anslis[r[0]] = now
print("Yes")
for i in range(2,len(anslis)):
    print(anslis[i])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
n,m=map(int,input().split())
g = nx.Graph()
for _ in range(m):
    x,y=map(int,input().split())
    g.add_edge(x,y)
l=[None]*(n-1)
for i in range(2,n+1):
    l[i-2] = nx.shortest_path(g, source=1, target=i)[-2]
if l:
    print("Yes")
    for x in l:
        print(x)
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import shortest_path
import numpy as np
import sys

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

N, M = map(int, input().split())
A = []
B = []
neighbor = np.array([[0 for x in range(N)] for y in range(N)])
for i in range(M):
    a, b = map(lambda x: int(x)-1, input().split())
    neighbor[a][b] = 1
    neighbor[b][a] = 1

d, p = shortest_path(neighbor, return_predecessors=True)

ans = []


for i in range(1,N):
    next_sign = get_path(0,i,p)
    if next_sign:
        ans.append(next_sign[-2]+1)
    else:
        print("No")
        sys.exit(0)
print("Yes")

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