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 = map(int,input().split())
l = [[0 for x in range(2)] for y in range(m)]
for i in range(m):
    l[i] = list(map(int,input().split()))
l2 = [m+1 for x in range(n)]
l2[0] = 1
l3 = [0 for x in range(n)]
key = 1
while (max(l2) == m+1):
    for j in range(m):
        x1 = l[j][0]
        x2 = l[j][1]
        if l2[x1-1] == key:
            l2[x2-1] = min(key+1,l2[x2-1])
            if l2[x2-1] == key+1:
                l3[x2-1] = l[j][0]
        elif l2[x2-1] == key:
            l2[x1-1] = min(key+1,l2[x1-1])
            if l2[x1-1] == key+1:
                l3[x1-1] = l[j][1]
    key += 1
print("Yes")
for k in range(n-1):
    print(l3[k+1])

Submission status: Time Limit Exceeded

Solution code:
#from pprint import pprint
#from collections import defaultdict
#from collections import Counter
#from copy import deepcopy
#from itertools
#import sys 
#sys.setrecursionlimit(N) #N回まで再起を許可する。

# = map(int,input().split())

# = list(map(int,input().split()))

# = [list(map(int,input().split())) for _ in range(XXXX)]

from collections import deque






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

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

ab_count = {key:[] for key in range(1,n+1)}

for i in range(m):
    ab_count[ab_list[i][0]].append(ab_list[i][1])
    ab_count[ab_list[i][1]].append(ab_list[i][0])


#print(ab_count)

que = deque()

#始点は1、階層は0からスタート
que.append([1,0])

checked_dict = {key:[] for key in range(1,n+1)}
temp_dict = {key:[] for key in range(1,n+1)}
where = 0

while que:
    x_pop = que.popleft()
    x = x_pop[0]
    if where != x_pop[1]:
        #階層が代わったから、temp_dictをchecked_dictへ反映させる処理
        for k in range(1,n+1):
            if len(checked_dict[k]) == 0:
                checked_dict[k] = temp_dict[k]
            else:
                aaa = set(checked_dict[k]) & set(temp_dict[k])
                if aaa != set():
                    checked_dict[k] = list(aaa)

    
    where = x_pop[1]

    for j in ab_count[x]:
        if len(checked_dict[j]) == 0:
            #OK,temp_dictに入れて、queに入れる。
            temp_dict[j].append(x)
            que.append([j,where+1])
        else:
            continue

    

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

Submission status: Time Limit Exceeded

Solution code:
def inp():exec('global inppp\ninpmoto,inppp=input().split(),[]\nfor i in inpmoto:\n try:inppp.append(int(i))if float(i).is_integer()else inppp.append(float(i));\n except:\n  try:inppp.append(str(i))\n  except:print("error in inp")');return inppp[0]if len(inppp)==1else list(inppp)
n, m = inp()
a = []
b = []
for i in range(m):
    miti = inp()
    a.append(miti[0])
    b.append(miti[1])
risuto = ["Yes"]+[None for i in range(n-1)]
tuginoheya = []
def main(heya):
    popsuru = []
    for i in range(len(a)):
            popsuru = []
            if a[i] == heya:
                if risuto[b[i] - 1] is None:
                    risuto[b[i] - 1] = heya
                    tuginoheya.append(b[i])
                    popsuru.append(i)
            elif b[i] == heya:
                if risuto[a[i] - 1] is None:
                    risuto[a[i] - 1] = heya
                    tuginoheya.append(a[i])
                    popsuru.append(i)
    for i in popsuru:
        a.pop(i)
        b.pop(i)
main(1)
for i in tuginoheya:
    main(i)

if None in risuto:
    print("No")
else:
    for i in risuto:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
def dijkstra_back(s,t,n,w,cost):
    #sからtへの最短経路の経路復元
    prev = [s] * n #最短経路の直前の頂点
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
        
        for i in range(n):
            if d[i] > d[v] + cost[v][i]: 
                d[i] = d[v] + cost[v][i]
                prev[i] = v
        
    path = [t]
    while prev[t] != s:
        path.append(prev[t])
        prev[t] = prev[prev[t]]
    path.append(s)
    path = path[::-1]
    return path

################################
n,w = map(int,input().split()) #n:頂点数　w:辺の数

List =[0]

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())
    z=1
    cost[x-1][y-1] = z
    cost[y-1][x-1] = z

for i in range(1,n):
    List.append(dijkstra_back(0,i,n,w,cost))
#    print(List[len(List)-2]+1)
#    print(dijkstra_back(0,i,n,w,cost))

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

Submission status: Time Limit Exceeded

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

#隣接リスト
adjacency_list=[[] for i in range(n)]
for i in range(m):
    a,b=map(int, input().split())
    adjacency_list[a-1].append(b-1)
    adjacency_list[b-1].append(a-1)

#i番目が、1からの距離がiのリスト
dist_list=[set([0])]
#i番目が、1から部屋までの距離
#dist_list2=[float("inf")]*n
#dist_list2[0]=0
#目印をつける方向
flag_list=[0]*(n-1)
#処理が終わってない部屋の集合
task_list=set([int(i) for i in range(1,n)])

while len(task_list)!=0:
    for i in dist_list[-1]:
        #iはひとつ距離が短い部屋の番号
        tmp=set([])
        for j in adjacency_list[i]:
            #jは、iと隣接している部屋の番号
            if j in task_list:
            #if dist_list2[j] = float("inf"):
                #dist_list2[j]=#新しい距離
                tmp.add(j)
                flag_list[j-1]=i
                task_list.discard(j)
        dist_list.append(tmp)

print("Yes")
for i in flag_list:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
#import numpy as np
from collections import deque

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

#base = np.zeros((n,n))
#ans_base = np.zeros(n)
base = [[[0] for j in range(n)] for i in range(n)]
ans_base = [0]*n

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

while temp:
  a = temp.popleft()
  for i in range(n):
    if base[a][i] == 1:
      temp.append(i)
      if ans_base[i] == 0:
        ans_base[i] = a+1
      base[i][a] = 0

ans_ini = "Yes"

if 0 in ans_base[1:]:
  ans_ini = "No"
  
print(ans_ini)

if ans_ini == "Yes":
  for i in range(1,n):
    print(int(ans_base[i]))

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(d):
	for k in range(N):
		for i in range(N):
			for j in range(N):
				d[i][j] = min(d[i][j], d[i][k] + d[k][j])
	return d
	
N,M = map(int,input().split())
d = [[float("inf")]*N for i in range(N)]
lines = []
for i in range(M):
	lines.append(list(map(int,input().split())))
	d[lines[i][0]-1][lines[i][1]-1] = 1
	d[lines[i][1]-1][lines[i][0]-1] = 1
for i in range(N):
	d[i][i] = 0
warshall_floyd(d)

count1 = 0
count2 = 1
H = [-1]*N
H[0] = 0
P = [-1]*N
l = []
while count1 < N-1:
	lnext =[]
	if count2 == 1:
		l.append(0)
	for i in range(M):
		if (lines[i][0]-1 in l and H[lines[i][1]-1] == -1):
			count1 += 1
			lnext.append(lines[i][1]-1)
			P[lines[i][1]-1] = lines[i][0]
			H[lines[i][1]-1] = count2
		if lines[i][1]-1 in l and H[lines[i][0]-1] == -1:
			count1 += 1
			lnext.append(lines[i][0]-1)
			P[lines[i][0]-1] = lines[i][1]
			H[lines[i][0]-1] = count2
	count2 += 1
	l = lnext
count3 = 0
for i in range(1,N):
	if H[i] == d[0][i]:
		count3 += 1
if count3 == N-1:
	print('Yes')
	for i in range(1,N):
		print(P[i])
else:
	print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

import networkx as nx

YES = "Yes"  # type: str
NO = "No"


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    G = nx.Graph()
    G.add_nodes_from([1+n for n in range(N)])

    G.add_edges_from([(a,b) for a,b in zip(A,B)])

    paths = nx.predecessor(G, 1, cutoff=N)

    print(YES)

    ans_list = []
    for key, val in sorted(paths.items()):
        if key != 1:
            print(val[0])
            # ans_list.append((key,val[0]))

    # ans_list.sort(key=lambda x: x[0])
    # for key, val in ans_list:
    #     print(val)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math
from collections import deque

import time

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

graph = []

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

d = deque()
d.append(1)

guidepost = [-1] * (n+1)

while d:
  v = d.popleft()
  for i, j in graph:
    if dist[i] != -1 and dist[j] != -1:
      continue
    elif i == v:
      dist[j] = 1
      d.append(j)
      if guidepost[j] != -1:
        print("No")
        exit()
      else:
        guidepost[j] = v
    elif j == v:
      dist[i] = 1
      d.append(i)
      if guidepost[i] != -1:
        print("No")
        exit()
      else:
        guidepost[i] = v
  
for i in range(2, n+1):
  if guidepost[i] == -1:
    print("No")
    exit()

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

Submission status: Time Limit Exceeded

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

def main():
  N, M = map(int, readline().split())
  n = {}
  m = {}
  A = []
  for i in range(N):
    n[i+1] = -1
    m[i+1] = -1
  n[1] = 0
  m[1] = 0
  for i in range(M):
    ai, bi = map(int, readline().split())
    A.append([ai, bi])
  cnt = 1
  depth = 0
  while cnt < N:
    d = []
    next = []
    for j in range(N):
      if n[j+1] == depth:
        d.append(j+1)
    for i in range(len(A)):
      if A[i][0] in d and n[A[i][1]] == -1:
        n[A[i][1]] = depth + 1
        m[A[i][1]] = A[i][0]
        cnt += 1
      elif A[i][1] in d and n[A[i][0]] == -1:
        n[A[i][0]] = depth + 1
        m[A[i][0]] = A[i][1]
        cnt += 1
      elif n[A[i][0]] == -1 or n[A[i][1]] == -1:
        next.append(A[i])
    A = next
    depth += 1
    if len(next) == 0:
      break
    elif depth > N:
      break
  if cnt == N:
    print('Yes')
    for i in range(1, N):
      print(m[i+1])
  else:
    print('No')

if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
room, route_count = map(int,input().split())
route = np.array([list(map(int,input().split())) for _ in range(route_count)])

object_nums = [1]
ans = [0]*(room-1)

def mem_ans(ans, object_num, next):
    if next is not None:
      for n in next:
        if ans[n-2] == 0:
          ans[n-2] = object_num
    return ans

for object_num in object_nums:
    object_rows = route[np.any(route==object_num, axis=1)]
    route[np.any(route==object_num, axis=1)] = 0
    next = object_rows[object_rows!=object_num]
    ans = mem_ans(ans, object_num, next)
    object_nums.extend(next)

if 0 in set(ans):
  print('No')
else:
  print('Yes')
  for i in ans:
    print(i)

Submission status: Time Limit Exceeded

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

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

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

Submission status: Time Limit Exceeded

Solution code:
s = input().split()

N = int(s[0])
M = int(s[1])

A = []
B = []

for i in range(M):
  t = input().split()
  A.append(int(t[0]))
  B.append(int(t[1]))

now = 1
d = []
for i in range(N):
  d.append(M*2)
d[0] = 0
Q = []
for i in range(N):
  Q.append(i+1)

result = []
for i in range(N):
  result.append(0)
    
while(len(Q) != 0 and not all([k != 0 for k in result[1:]])):
#while(len(Q) != 0):
  mi = 0
  le = 3 * M
  for i in Q:
    if d[i-1] < le:
      le = d[i-1]
      mi = i
  Q.remove(mi)
  
  for k in range(len(A)):
    if A[k] == mi and result[B[k]-1] == 0:
      result[B[k]-1] = mi
      d[B[k]-1] = d[mi-1] + 1
      #A.pop(k)
      #B.pop(k)
    elif B[k] == mi and result[A[k]-1] == 0:
      result[A[k]-1] = mi
      d[A[k]-1] = d[mi-1] + 1
      #A.pop(k)
      #B.pop(k)

if all([k != 0 for k in result[1:]]):
  print("Yes")
  for i in result[1:]:
    print(i)
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M  = map(int,input().split())
arr = [[] for _ in range(N+1)]
for _ in range(M):
  a,b = map(int,input().split())
  arr[a].append(b)
  arr[b].append(a)
visited = [0]*(N+1)
deque = deque([1])
ans = [0]*(N+1)

while list(deque)!=[]:
  for v in list(deque):
    visited[v] = 1
  if sum(visited)==N:
    break
  for v in list(deque):
    deque.popleft()
    for nb in arr[v]:
      if visited[nb]==0:
        deque.append(nb)
        ans[nb] = v

if sum(visited)==N:
  print('Yes')
  for a in ans[2:]:
    print(a)
else:
  print('No')

Submission status: Time Limit Exceeded

Solution code:
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

l = inlt()
n = l[0]
m = l[1]

rooms = []
for i in range(n):
    rooms.append([])

for i in range(m):
    tmp = inlt()

    a = tmp[0]
    b = tmp[1]

    rooms[a-1].append(b)
    rooms[b-1].append(a)

#print(rooms)
not_sorted = []
for i in range(1,n):
    not_sorted.append(i)
ans = [0] * n
clear = [0]
while(clear):
    clear_room = clear[0]
    clear.pop(0)
    to_be_removed = []
    for x in not_sorted:
        if(clear_room+1 in rooms[x]):
            ans[x] = clear_room
            clear.append(x)
            to_be_removed.append(x)
    for x in to_be_removed:
        not_sorted.remove(x)

if(len(not_sorted) != 0):
    print("No")
else:
    print("Yes")
    for i in range(1,n):
        print(ans[i]+1)

Submission status: Time Limit Exceeded

Solution code:
N, M = [int(x) for x in input().split(' ')]
paths = []
for _ in range(M):
  pa = [int(x) for x in input().split(' ')]
  paths.append(pa)

signs = [0 for _ in range(N)]
signs[0] = -1
 
def add_paths(i):
  query = []
  delete = []
  for j, p in enumerate(paths):
    if p[0] == i:
      a = signs[p[1] - 1]
      delete.append(j)
      if a == 0: 
        signs[p[1] - 1] = i
        query.append(p[1])
    elif p[1] == i:
      a = signs[p[0] - 1]
      delete.append(j)
      if a == 0:
        signs[p[0] - 1] = i
        query.append(p[0])
  for d, k in enumerate(delete):
    del paths[k - d]
  return query 


queue = [1]
while queue:
  m = queue[0]
  for z in add_paths(m):
    if z not in queue:
      queue.append(z)
  del queue[0]

signs = signs[1:]

if signs.count(0) > 0:
  print("No")
else:
  print("Yes")
  for s in signs:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline 
sys.setrecursionlimit(10 ** 6)

N,M = map(int,input().split())
path = [[] for i in range(N)]
inf = 10 ** 6 * 2

ans = [[None,inf] for i in range(N - 1)]

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

def dfs(cur,par,con):
  if con == N + 1:
    return
  for chi in path[cur]:
    if chi == par:
      continue
    if con < ans[chi - 1][1]:
      ans[chi - 1][0] = cur
      ans[chi - 1][1] = con + 1
      dfs(chi,cur,con + 1)

dfs(0,-1,0)

if all([i[0] != None for i in ans]):
  print("Yes")
  for i in range(N - 1):
    print(ans[i][0] + 1)
else:
  print("No")

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:
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
INF = 10**18

def bfs(start):
    d = [INF]*n
    d[start] = 0
    q = collections.deque([])
    q.append(start)
    pre = [0]*(n)
    while q:
        c = q.popleft()
        next_v = edge[c]
        for v in next_v:
            if v == 0 and start != 0:
                d[v] = d[c]+1
                pre[v] = c
                return [pre,d]
            if d[v] == INF and v != c:
                q.append(v)
                d[v] = d[c]+1
                pre[v] = c
    #経路を復元したい
    return [pre,d]
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(b)
    edge[b].append(a)
judge = bfs(0)
flag = judge[1]
for i in flag:
    if i == INF:
        print("No")
        sys.exit()
print("Yes")
for i in range(1,n):
    ans = bfs(i)
    if ans[1][0] == 1:
        print("1")
    else:
        print(ans[0][0] + 1)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
sys.setrecursionlimit(10**7)
def run():
    N, M = map(int, sysread().split())
    to = [[] for _ in range(N+1)]
    AB = list(map(int, read().split()))
    A = AB[::2]
    B = AB[1::2]
    for a,b in zip(A,B):
        to[a].append(b)
        to[b].append(a)

    seen = [False] * (N+1)
    stack = []
    seen[1] = True
    heappush(stack, (0, 1, 0))# (distance, node, prev)
    mark = [0] * (N+1)
    done = [False] * (N+1)

    while stack:
        dist, current, prev = heappop(stack)
        seen[current] = True
        if not done[current]:
            done[current] = True
            mark[current] = prev
        for next in to[current]:
            if not seen[next]:
                heappush(stack, (dist+1, next, current))

    print('Yes')
    mark = [str(val) for val in mark]
    print('\n'.join(mark[2:]))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import os
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from io import BytesIO, IOBase
from typing import Dict, List, Optional, Set, Tuple


def solve(values: List[Tuple[int, int]], n: int) -> List[int]:
    passages = defaultdict(set)
    for a, b in values:
        passages[a].add(b)
        passages[b].add(a)
    to_visit = deque((1,))
    visited = set()
    # 0 idx is not used
    distances = [n + 1] * (n + 1)
    distances[1] = 0
    signs = [1] * (n + 1)
    while to_visit:
        cur = to_visit.popleft()
        for neighbour in passages[cur]:
            tmp = distances[cur] + 1
            if tmp < distances[neighbour]:
                distances[neighbour] = tmp
                signs[neighbour] = cur
            if neighbour not in visited:
                to_visit.append(neighbour)
        visited.add(cur)
    # LOG.debug((visited))
    # LOG.debug((distances))
    if len(visited) < n:
        return []
    return signs[2:]


def do_job(stdin, stdout):
    "Do the work"
    LOG.debug("Start working")
    N, M = map(int, stdin.readline().split())
    values = []
    for _ in range(M):
        a, b = map(int, stdin.readline().split())
        values.append((a, b))
    result = solve(values, N)
    if not result:
        print("No", file=stdout)
    else:
        print("Yes", file=stdout)
        print("\n".join(map(str, result)), file=stdout)


def print_output(testcase: int, result, stdout) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result), file=stdout)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result), file=stdout)


BUFSIZE = 8192


class FastIO(IOBase):
    # pylint: disable=super-init-not-called, expression-not-assigned
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    # pylint: disable=super-init-not-called
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(IOWrapper(sys.stderr))
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    stdin = IOWrapper(sys.stdin)
    stdout = IOWrapper(sys.stdout)
    do_job(stdin, stdout)
    stdout.flush()
    for h in LOG.handlers:
        h.flush()
    return 0


if __name__ == "__main__":
    sys.exit(main())

Submission status: Time Limit Exceeded

Solution code:
# from collections import defaultdict
import numpy as np
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())
a, b = [], []
for _ in range(m):
    ai, bi =  map(int, input().split())
    a.append(ai)
    b.append(bi)

graph = [[0 for _ in range(n)] for _ in range(n)]
for ai, bi in zip(a, b):
    graph[ai - 1][bi - 1], graph[bi - 1][ai - 1] = 1, 1
graph = np.array(graph)
signs = [set() for _ in range(n)]
# print(graph)
shortest, pathes = shortest_path(graph, return_predecessors=True)
# print(shortest)
# print(pathes)
for i in range(1, n):
    path = get_path(i, 0, pathes)
    # print(i, path)
    # print(get_path(i, 0, pathes)[1:-1])
    for j in range(len(path) - 1):
        # print(f'{path[j + 1]} is signed at {path[j]}')
        signs[path[j]].add(path[j + 1])
# print(signs)

is_ok = True
for sign in signs:
    if len(sign) > 1:
        is_ok = False
        break

if is_ok:
    print('Yes')
    for sign in signs[1:]:
        print(sign.pop() + 1)
else:
    print('No')

Submission status: Time Limit Exceeded

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

import networkx as nx

YES = "Yes"  # type: str
NO = "No"


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    G = nx.Graph()
    G.add_nodes_from([1+n for n in range(N)])

    G.add_edges_from([(a,b) for a,b in zip(A,B)])

    paths = nx.predecessor(G, 1)

    print(YES)

    ans_list = []
    for key, val in sorted(paths.items()):
        if key != 1:
            print(val[0])
            # ans_list.append((key,val[0]))

    # ans_list.sort(key=lambda x: x[0])
    # for key, val in ans_list:
    #     print(val)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int,input().split())
r = [list(map(int,input().split())) for i in range(m)]
inf = 9999999
la = [[] for i in range(n + 1)]
for i,j in r:
    la[i].append(j)
    la[j].append(i)

p = [0 for i in range(n+1)]
ex = [inf for i in range(n+1)]
do = []
ex[1] = 1

do.append(1)

while(len(do) != 0):
    x = do.pop(-1)
    
    for i in la[x]:
        if ex[i] > ex[x]:
            do.append(i)
            ex[i] = ex[x]+1
            p[i] = x

if ex.count(inf) > 1:
    print("No")
    exit()
    
print("Yes")
for i in range(2,n+1):
    print(p[i])

Submission status: Time Limit Exceeded

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

roots = [input().split(' ') for _ in range(m)]
for i in range(m):
    roots[i] = [int(x)-1 for x in roots[i]]

dic = {}
all_list = [0]
is_no = False
for i in range(n):
    if len(dic) >= n-1:
        break
    d_list = []
    a = 0
    while a < m:
        is_next = True
        for b in range(2):
            if roots[a][b] in all_list:
                if dic.get(roots[a][abs(b-1)]) == None:
                    d_list.append(roots[a][abs(b-1)])
                    dic[roots[a][abs(b-1)]] = roots[a][b] + 1
                roots.pop(a)
                m -= 1
                is_next = False
                break
        if is_next:
            a += 1
    if len(d_list) == 0:
        is_no = True
        break
    all_list += d_list

if is_no:
    print('No')
else:
    print('Yes')
    for i in range(1, n):
        print(dic[i])