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:
import numpy as np
a = list(map(int,input().split()))
k = []
count = []
for i in range(0,a[0]) :
    k.append([])
    count.append([])
for i in range(0,a[1]) :
    b = list(map(int,input().split()))
    k[b[0]-1].append(b[1])
    k[b[1]-1].append(b[0])

an = []
room = []
for i in range(0,a[0]) :
    if i == 0 :
        an.append(0)
    else :
        an.append(-1)
for i in range(0,a[0]+1) :
    room.append(an)
    '''
room.append(an)
an = []
for i in range(0,a[0]) :
    an.append(-1)
for i in range(0,a[0]) :
    room.append(an)
    '''
room = np.array(room).tolist()

for i in range(1,a[0]+1) :
    for j in range(0,a[0]) :
        if 1 in count[j] :
            continue
        if room[i-1][j] != -1 :
            room[i][j] = room[i-1][j]
        if room[i-1][j] == -1 : 
            continue
        else :
            count[j].append(1)
            for m in k[j] :
                if room[i-1][m-1] == -1 :
                    if room[i][m-1] == -1 :
                        room[i][m-1] = j + 1
                    else :
                        continue
                else :
                    room[i][m-1] = room[i-1][m-1]
    #print(count)
    #print(room)
    if room[i] == room[i-1] :
        room = room[:i]
        break

ans = room[len(room)-1][1:]
if min(ans) < 0 :
    print("No")
else :
    print("Yes")
    for i in ans :
        print(i)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
a = list(map(int,input().split()))
k = []
for i in range(0,a[0]) :
    k.append([])
for i in range(0,a[1]) :
    b = list(map(int,input().split()))
    k[b[0]-1].append(b[1])
    k[b[1]-1].append(b[0])

an = []
room = []
for i in range(0,a[0]) :
    if i == 0 :
        an.append(0)
    else :
        an.append(-1)
room.append(an)
an = []
for i in range(0,a[0]) :
    an.append(-1)
for i in range(0,a[0]) :
    room.append(an)
room = np.array(room).tolist()

for i in range(1,a[0]+1) :
    for j in range(0,a[0]) :
        if room[i-1][j] != -1 :
            room[i][j] = room[i-1][j]
        if room[i-1][j] == -1 :
            continue
        else :
            for m in k[j] :
                if room[i-1][m-1] == -1 :
                    if room[i][m-1] == -1 :
                        room[i][m-1] = j + 1
                    else :
                        continue
                else :
                    room[i][m-1] = room[i-1][m-1]
    if room[i] == room[i-1] :
        room = room[:i]
        break

ans = room[len(room)-1][1:]
if min(ans) < 0 :
    print("No")
else :
    print("Yes")
    for i in ans :
        print(i)

Submission status: Time Limit Exceeded

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

arrow = [0]*(N-1)
list1 = [1]
list_total = [1]
s = 0
for j in range(N):
  if s == N-1:
    break
  
  list2 = []
  for x in list1:
    for i in range(M):
      if route[i][0] == x and route[i][1] not in list_total:
        arrow[route[i][1]-2] = x
        list2.append(route[i][1])
        list_total.append(route[i][1])
        s = s+1
      if route[i][1] == x and route[i][0] not in list_total:
        arrow[route[i][0]-2] = x
        list2.append(route[i][0])
        list_total.append(route[i][0])
        s = s+1
      
  list1 = list2
print('Yes')
for y in arrow:
  print(y)

Submission status: Time Limit Exceeded

Solution code:
import sys
inf = 10**9
sys.setrecursionlimit(inf)


def connect(signs, to_room, from_room):
    signs[to_room][2].add(from_room)
    signs[from_room][2].add(to_room)
    return signs


def update(signs, to_room, from_room):
    """
    1. fromの距離を記憶
    2. fromの行き先を記憶
    3. toの来るリストにfromを追加
    4. fromの行き先にtoを追加
    5. fromの距離をto+1に変更
    6. もともとのfromの距離がinfなら
        a. fromの来るリスト(fromfrom)の行き先をfromにする
        b. fromfromの来るリストからfromを削除
        c. 1から始める
    7. fromの新しい距離がもともとのfromの行き先(fromto)の距離がより短いなら、
        a. 1から始める
    """
    # from_room_dist = signs[from_room][0]
    # from_to_rooms = signs[from_room][1]
    # signs[to_room][2].add(from_room)
    # signs[to_room][2].discard(from_room)
    signs[from_room][0] = signs[to_room][0] + 1
    signs[from_room][1] = to_room
    # signs[from_room][2].discard(to_room)
    for from_from_room in signs[from_room][2]:
        if signs[from_room][0] < signs[from_from_room][0] - 1:
            signs = update(signs, from_room, from_from_room)
    # if from_room_dist == inf:
    #     for from_from_room in signs[from_room][1]:
    #         signs[from_from_room][1].discard(from_room)
    #         signs = update(signs, from_room, from_from_room)
    for from_to_room in signs[from_room][2]:
        if from_to_room and signs[from_room][0] < signs[from_to_room][0] - 1:
            signs = update(signs, from_room, from_to_room)
        # print(signs)
    return signs


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

    signs = [[], [0, None, set()]] + [[inf, None, set()] for _ in range(n - 1)]
    for a, b in ab:
        # print(a, b)
        signs = connect(signs, a, b)
        a_dist = signs[a][0]
        b_dist = signs[b][0]
        # print(a_dist, b_dist)
        # if a_dist == b_dist:
        if a_dist < b_dist - 1:
            signs = update(signs, a, b)
        elif b_dist < a_dist - 1:
            signs = update(signs, b, a)
        # print(signs)

    del signs[0:2]
    is_yes = all([True if not i[0] == inf else False for i in signs])
    if is_yes:
        ans = ['Yes'] + [i[1] for i in signs]
    else:
        ans = ['No']
    ans = '\n'.join([str(i) for i in ans])

    print(ans)
    return(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

# 初期化周り
N, M = map(int, input().rstrip().split())
G = [[] for i in range(N+1)]
for i in range(M):
    A, B = map(int, input().rstrip().split())
    G[A].append(B)
    G[B].append(A)

# 目印
sign = [-1]*(N+1)
sign[0] = None
sign[1] = 0

queue = deque([1])

while queue:
    node = queue.popleft()
    for next in G[node]:
        if sign[next] > -1:
            continue
        sign[next] = node
        queue.append(next)

ans = "Yes"

for i in range(2, N+1):
    S = sign[i]
    while S > 0:
        S = sign[S]

    if not S == 0:
        ans = "No"

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

Submission status: Time Limit Exceeded

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

G = nx.Graph()
G.add_nodes_from(range(1,room+1))
G.add_edges_from(route)
shortest_path_dict = nx.single_target_shortest_path(G, target=1)

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m=map(int,input().split())
cost = [[float("inf") for i in range(n)] for i in range(n)] 
to=[[] for i in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    to[x-1].append(y-1)
    to[y-1].append(x-1)
dist=[None]*n    

que=deque([0])
while que:
    v=que.pop()
    for i in to[v]:
        if(dist[i] is None):
            dist[i]=v+1
            que.appendleft(i)
        
print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m=map(int,input().split())
cost = [[float("inf") for i in range(n)] for i in range(n)] 
to=[[] for i in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    to[x-1].append(y-1)
    to[y-1].append(x-1)
dist=[1000000]*n    

que=deque([0])
while que:
    v=que.pop()
    for i in to[v]:
        if(dist[i] is 1000000):
            dist[i]=v+1
            que.appendleft(i)
        
print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m=map(int,input().split())
cost = [[float("inf") for i in range(n)] for i in range(n)] 
to=[[] for i in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    to[x-1].append(y-1)
    to[y-1].append(x-1)
dist=[1000000]*n    

que=deque([])
que.append(0)
while(len(que)):
    v=que.popleft()
    for i in to[v]:
        if(dist[i] is 1000000):
            dist[i]=v+1
            que.append(i)
        
print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Time Limit Exceeded

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

cost = [[float("inf") for i in range(n)] for i in range(n)] 
to=[[] for i in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    to[x-1].append(y-1)
    to[y-1].append(x-1)
dist=[1000000]*n    

que=[]
que.append(0)
while(len(que)):
    v=que.pop(0)
    for i in to[v]:
        if(dist[i] is 1000000):
            dist[i]=v+1
            que.append(i)
        
print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Time Limit Exceeded

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

cost = [[float("inf") for i in range(n)] for i in range(n)] 
to=[[] for i in range(n)]
for i in range(m):
    x,y = map(int,input().split())
    to[x-1].append(y-1)
    to[y-1].append(x-1)
dist=[0]*n    
flag=[False]*n
flag[0]=True
que=[]
que.append(0)
while(False in flag):
    v=que.pop(0)
    for i in to[v]:
        if(flag[i]==False):
            dist[i]=v+1
            flag[i]=True
            que.append(i)
        


print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Time Limit Exceeded

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

cost = [[float("inf") for i in range(n)] for i in range(n)] 

for i in range(m):
    x,y = map(int,input().split())
    cost[x-1][y-1] = 1
    cost[y-1][x-1] = 1

dist=[0]*n    
flag=[False]*n
flag[0]=True
que=[]
que.append(0)
while(False in flag):
    v=que.pop(0)
    tmp=copy.deepcopy(que)
    for i in range(n):
        if(cost[v][i]==1 and flag[i]==False):
            dist[i]=v+1
            flag[i]=True
            que.append(i)
    if(tmp==que):
        print("No")
        exit()
print("Yes")
for i in dist[1:]:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
#n,m=map(int,input().split())
#r=np.array([list(map(int,input().split())) for _ in range(m)])
n, m, *r = map(int, open(0).read().split())
r = np.array(r).reshape(-1,2)
#n,m=10**1,10**1-1
#r=np.array([[i+1,i+2] for i in range(m)])

start=np.array([1], dtype='int64')
done=np.array([1], dtype='int64')
ans=np.array([-1]*n, dtype='int64')

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
t = {i: set() for i in range(1, n + 1)}
v = [-1] * n

for _ in range(m):
    a, b = map(int, input().split())
    t[a].add(b)
    t[b].add(a)
q.append(1)
v[0] = 1
while q:
    next = q.popleft()
    for i in t[next]:
        if v[i - 1] == -1 and i not in q:
            q.append(i)
            v[i - 1] = next
print('Yes')
print(*v[1:], sep='\n')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
t = {i: set() for i in range(1, n + 1)}
v = [0] * n
p = [0] * n

for _ in range(m):
    a, b = map(int, input().split())
    t[a].add(b)
    t[b].add(a)
q.append(1)
while q:
    next = q.popleft()
    v[next -1] = 1
    for i in t[next]:
        if v[i - 1] == 0:
            q.append(i)
            if p[i - 1] == 0:
                p[i - 1] = next
print('Yes')
print(*p[1:], sep='\n')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
t = {i: set() for i in range(1, n + 1)}
v = [0] * n
p = [0] * n

for _ in range(m):
    a, b = map(int, input().split())
    t[a].add(b)
    t[b].add(a)
q.append(1)
while q:
    next = q.popleft()
    v[next -1] = 1
    for i in t[next]:
        if v[i - 1] == 0 and i not in q:
            q.append(i)
            p[i - 1] = next
print('Yes')
print(*p[1:], sep='\n')

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
t = {i: set() for i in range(1, n + 1)}
v = [0] * n
p = [0] * n

for _ in range(m):
    a, b = map(int, input().split())
    t[a].add(b)
    t[b].add(a)

v[0] = 1
for i in t[1]:
    p[i - 1] = 1
    q.append(i)
while q:
    next = q.popleft()
    v[next -1] = 1
    for i in t[next]:
        if v[i - 1] == 0:
            q.append(i)
            if p[i - 1] == 0:
                p[i - 1] = next
print('Yes')
print(*p[1:], sep='\n')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
t = {i: set() for i in range(1, n + 1)}
v = [0] * n
p = [0] * n

for _ in range(m):
    a, b = map(int, input().split())
    t[a].add(b)
    t[b].add(a)

v[0] = 1
for i in t[1]:
    p[i - 1] = 1
    q.append(i)
while q:
    next = q.popleft()
    v[next -1] = 1
    for i in t[next]:
        if v[i - 1] == 0 and i not in q:
            q.append(i)
            p[i - 1] = next
print('Yes')
print(*p[1:], sep='\n')

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
N,M=map(int, input().split())
l=[[0]*N for i in range(N)]
for i in range(M):
  a ,b = map(int, input().split())
  l[a-1][b-1]=1
  l[b-1][a-1]=1
dij =dijkstra(l)[0]
ans = []
for i in range(N):
  if not i == 0:
    mitukatta=False
    for j in range(N):
      if l[i][j]==1 and dij[j]==dij[i]-1:
        direc=j
        mitukatta=True
    if not mitukatta:
      print("No")
      sys.exit()
    ans.append(direc+1)
print("Yes")
for a in ans:
  print(a)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = list(map(int, input().split()))
connects = [[0] * n for _ in range(n)]
for _ in range(m):
    i, j = list(map(int, input().split()))
    connects[i - 1][j - 1] = 1
    connects[j - 1][i - 1] = 1
stack = deque([0, ])
visited = [-1] * n
while stack:
    x = stack.popleft()
    connects_with_x = [i for i in range(n) if connects[x][i] == 1]
    for dx in connects_with_x:
        if visited[dx] == -1:
            visited[dx] = x
            stack.append(dx)
        else:
            continue
print('Yes')
[print(i + 1) for i in visited[1:]]

Submission status: Time Limit Exceeded

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

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

A = list(map(lambda x: x-1, A))
B = list(map(lambda x: x-1, B))

ans = [0]*N
ans =list(map(lambda x: x-1, ans))
ans[0]=-2

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

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

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

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

Submission status: Time Limit Exceeded

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

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

A = A-1
B = B-1

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

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

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

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

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

Submission status: Time Limit Exceeded

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

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

for i in range(m):
    ll[l[i][0]-1].append(l[i][1])
    ll[l[i][1]-1].append(l[i][0])

lt=[0 for i in range(n)]
lll=[1]
for i in range(n):
    for j in ll[lll[i]-1]:
        lll.append(j)
        if (j!=1 and lt[j-1]==0):
            lt[j-1]=lll[i]
    lll=list(dict.fromkeys(lll))

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M=map(int,input().split())
A=np.zeros(N)
B=np.zeros([M,2])
for i in range(M):
  k,l=map(int,input().split())
  B[i,0]=k
  B[i,1]=l

C={1}
D=set()
E=[]
while len(C)<N:
  for i in range(B.shape[0]):
    if B[i,0] in C:
      if A[int(B[i,1])-1]==0:
        A[int(B[i,1])-1]=B[i,0]
        D.add(B[i,1])
      E.append(i)
    elif B[i,1] in C:
      if A[int(B[i,0])-1]==0:
        A[int(B[i,0])-1]=B[i,1]
        D.add(B[i,0])
      E.append(i)
  B=np.delete(B,E,0)
  E=[]
  C=C|D
  D=set()

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

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
road = []
near = [[1]]###ゴールへの近道、段階的にリストにしたい。
sign = [0]*(N+1)###簡単のため。最後にsign[0],sign[1]は0になってるから排除できる。
for i in range(M):###入力値の読み取り
    A_i,B_i = map(int, input().split())
    road.append([A_i,B_i])###二重リスト、道の両端がリスト内の値
    #if A_i == 1: ###最後に出力するやつを作ってる。
        #sign[B_i] == 1
       # near[0].append[B_i]
    #if B_i == 1:
       # sign[A_i] == 1
        #near[0].append[A_i]
#print(road)###うまくいってる
j = 0
while len(near[j]) != 0:###near[j]に要素がある時、
    near.append([])
    #print(road)
    for i in near[j]:###near[j]の要素ごとに、要素と繋がってる部屋を検索。色々する
        rem = []###要素ごとにremリストを作る
        #print(i)
        for k in road:###roadでnear[j]すなわち(i)と繋がってる部屋の値を取得(roadの片方がnear[j]の要素なら繋がっている)
            #print(k)
            if k[0] == i:###roadの片方がnear[j]の要素(i)の時
                if sign[k[1]] == 0:###sign[k[1]]が0の時、（上書き防止）
                    sign[k[1]] = i ###roadのもう片方の部屋の道標は(i)
                near[j+1].append(k[1])###nearの次の段階の部屋にroadの(i)じゃない方を追加
                rem.append(road.index(k))###roadの使った要素は後から削除
            if k[1] == i:###roadのもう片方が(i)の時
                if sign[k[0]] == 0:
                    sign[k[0]] = i
                near[j+1].append(k[0])
                rem.append(road.index(k))
        #print(rem)
        #print(road)
        rem.sort(reverse=True)
        for num in rem:###remの数字の要素をroadから削除
            del road[num]
        #print(road)
    j += 1
if len(road) == 0:
    print('Yes')
    for i in range(len(sign)):
        if sign[i] != 0:
            print(sign[i])
else:
    print('No')
#print(road)
#print(near)
#print(sign)###signは上書きされてはいけない

Submission status: Time Limit Exceeded

Solution code:

import numpy as np
from scipy.sparse.csgraph import breadth_first_tree, breadth_first_order
from scipy.sparse import csr_matrix
N, M = map(int,input().split())
l = [[0]*(N) for _ in range(N)]
for i in range(M):
    A, B = map(int,input().split())
    l[A-1][B-1] = 1
    l[B-1][A-1] = 1

csr = csr_matrix(l)
Tcsr = breadth_first_order(csr, 0, False, True)
ans = []
for i in Tcsr[1][1:]+1:
    if i == -9998:
        print("No")
        quit()
    ans.append(i)
print("Yes")
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:

from sys import stdin
from collections import deque


def main():
    N, M = [int(x) for x in stdin.readline().rstrip().split()]
    ipt = [[int(y) for y in x.rstrip().split()] for x in stdin.readlines()]
    MOD = 100100100100100100

    pl = [0] * (N + 1)

    for a, b in ipt:
        if pl[a] == 0:
            pl[a] = [b]
        else:
            pl[a].append(b)
        if pl[b] == 0:
            pl[b] = [a]
        else:
            pl[b].append(a)

    que = deque([1])
    deep = [MOD] * (N + 1)
    deep[1] = 0
    deep[0] = 0
    arrow = [0] * (N + 1)
    cnt = 1

    while not not que:
        q = que.popleft()
        tmp = False
        for i in pl[q]:
            if deep[i] != MOD:
                continue
            deep[i] = deep[q] + 1
            arrow[i] = q
            tmp = True
            cnt += 1
        if tmp:
            que.extend(pl[q])

    if N != cnt:
        print("No")
    else:
        print("Yes")
        for i in arrow[2:]:
            print(i)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# ANSHUL GAUTAM
# IIIT-D

from math import *
from copy import *					# ll = deepcopy(l)
from heapq import *					# heappush(hp,x)
from string import *				# alpha = ascii_lowercase
from random import *				# l.sort(key=lambda l1:l1[0]-l1[1]) => ex: sort on the basis difference
from bisect import *				# bisect_left(arr,x,start,end)  => start and end parameters are temporary
from sys import stdin				# bisect_left return leftmost position where x should be inserted to keep sorted
from sys import maxsize				# minn = -maxsize
from operator import *				# d = sorted(d.items(), key=itemgetter(1))
from itertools import *				# pre = [0] + list(accumulate(l))
from collections import Counter		# d = dict(Counter(l))
from collections import defaultdict # d = defaultdict(list)

'''

'''

def solve(adj):
	n = len(adj)
	dis = [maxsize]*n
	ans = [0]*n
	q = [0]
	dis[0] = 0
	while(q):
		src = q.pop(0)
		for nn in adj[src]:
			if(dis[nn] == maxsize):
				ans[nn] = src
				dis[nn] = dis[src] + 1
				q.append(nn)
			else:
				if(dis[nn] > dis[src] + 1):
					ans[nn] = src
					dis[nn] = dis[src] + 1
	for i in range(n):
		ans[i] += 1
	if(maxsize in dis[1:]):
		print('No')
	else:
		print('Yes')
		for i in range(1,n):
			print(ans[i])

N,M = list(map(int, stdin.readline().rstrip().split()))
adj = [[] for i in range(N)]
for _ in range(M):
	a,b = list(map(int, stdin.readline().rstrip().split()))
	a -= 1
	b -= 1
	adj[a].append(b)
	adj[b].append(a)
solve(adj)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
a, b = [], []
for i in range(m):
    ai, bi = map(int, input().split())
    a.append(ai-1)
    b.append(bi-1)

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


def bfs(start, a, b, signposts):
    stack = [start]
    while (stack):
        visiting = stack.pop(0)
        for i in range(m):
            if a[i] == visiting and signposts[b[i]-1] == -1:
                signposts[b[i]-1] = visiting
                stack.append(b[i])
            elif b[i] == visiting and signposts[a[i]-1] == -1:
                signposts[a[i]-1] = visiting
                stack.append(a[i])


bfs(0, a, b, signposts)

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

Submission status: Time Limit Exceeded

Solution code:
import heapq

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

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

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

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


def raw_input():
    return input()


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

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
from io import StringIO
import unittest
from collections import deque

# 参考：https://atcoder.jp/contests/abc168/submissions/13401646

def resolve():
    n, m = map(int, input().split())
    ms = [list(map(int, input().split())) for i in range(m)]

    # 各部屋のつながりを整理整頓する(添え字0は使わないので、+1して一つ多い配列を作成)
    roots = [[] for i in range(n + 1)]
    for i in ms:
        roots[i[0]].append(i[1])
        roots[i[1]].append(i[0])

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [99999 for i in range(n + 1)]
    aaa = [False for i in range(n + 1)]

    best_signs = [0 for i in range(n+1)]

    # 調べ終えた道を格納するタプル
    # searched = []

    # 初期値を代入
    que = deque()
    que.append(1)  # スタート地点
    deeps[1] = 0  # スタート地点の深さは0

    # BFS開始
    while not len(que) is 0:

        now = que.popleft()

        # 無限ループ防止のため調査済みフラグを立てる
        # searched.append(now)

        # 最適解を代入し続けて、適切な深さを求める
        for target in roots[now]:
            # 調査済みの道には何もしない。
            if aaa[target] is True:
                continue

            # 新しい道の場合。最適解を取得+キュー追加
            deeps[target] = deeps[now] + 1
            que.append(target)
            aaa[target] = True
            # 最適な道しるべを設定
            best_signs[target] = now

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    # del best_signs[0:2]

    ans = "Yes"
    for i in range(2, len(best_signs)):
        ans = ans + "\n" + str(best_signs[i])

    print(ans)


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """4 4
1 2
2 3
3 4
4 2"""
        output = """Yes
1
2
2"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6"""
        output = """Yes
6
5
5
1
1"""
        self.assertIO(input, output)


if __name__ == "__main__":
    # unittest.main()
    resolve()