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:
# 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,jit
# 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
from networkx import Graph,shortest_path,single_source_shortest_path
G = 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())
rows = [list(map(int,input().split())) for _ in range(M)]

G.add_edges_from(rows)

# shortestPath = shortest_path(G,target=1)
shortestPath = single_source_shortest_path(G,source=1)
# shortestPath = single_target_shortest_path(G,target=1)
# shortestPathLength,shortestPath = single_source_dijkstra(G,source=1)

# print(shortestPath)
if len(shortestPath) != N:
    print("No")
    exit()

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


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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = deque([] for k in range(M))
for k in range(M):
    L[k] = deque(map(int, input().split()))
nextvisit =[[1]]
visited =deque(0 for k in range(N))
visited[0]=1
not_used = deque(k for k in range(M))
for j in range(M-1):
    nextvisit.append([])
    for visit in nextvisit[0]:

        """
        print("L=",L)
        print("next=",nextvisit[j])
        print("not_used", not_used)
        """
        erase = []
        for k in not_used:
            if visit == L[k][1]:
                if visited[L[k][0]-1] == 0:
                    nextvisit[1].append(L[k][0])
                    visited[L[k][1]-1] = 1
                    visited[L[k][0]-1] = 1
                    room[L[k][0]-1] = L[k][1]
                erase.append(k)
                
            if visit == L[k][0]:
                if visited[L[k][1]-1] == 0:
                    nextvisit[1].append(L[k][1])
                    visited[L[k][0]-1] = 1
                    visited[L[k][1]-1] = 1
                    room[L[k][1]-1] = L[k][0]  
                erase.append(k)

        not_used = deque(set(not_used)-set(erase))
    del nextvisit[0]
    
    if len(not_used) == 0:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==2:
    print(1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = deque(map(int, input().split()))
nextvisit =[[1]]
visited =deque(0 for k in range(N))
visited[0]=1
not_used = deque(k for k in range(M))
for j in range(M-1):
    nextvisit.append([])
    for visit in nextvisit[0]:

        """
        print("L=",L)
        print("next=",nextvisit[j])
        print("not_used", not_used)
        """
        erase = []
        for k in not_used:
            if visit == L[k][1]:
                if visited[L[k][0]-1] == 0:
                    nextvisit[1].append(L[k][0])
                    visited[L[k][1]-1] = 1
                    visited[L[k][0]-1] = 1
                    room[L[k][0]-1] = L[k][1]
                erase.append(k)
                
            if visit == L[k][0]:
                if visited[L[k][1]-1] == 0:
                    nextvisit[1].append(L[k][1])
                    visited[L[k][0]-1] = 1
                    visited[L[k][1]-1] = 1
                    room[L[k][1]-1] = L[k][0]  
                erase.append(k)

        not_used = deque(set(not_used)-set(erase))
    del nextvisit[0]
    
    if len(not_used) == 0:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==2:
    print(1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[1]]
visited =[0 for k in range(N)]
visited[0]=1
not_used = [k for k in range(M)]
for j in range(M-1):
    nextvisit.append([])
    for visit in nextvisit[0]:

        """
        print("L=",L)
        print("next=",nextvisit[j])
        print("not_used", not_used)
        """
        erase = []
        for k in not_used:
            if visit == L[k][1]:
                if visited[L[k][0]-1] == 0:
                    nextvisit[1].append(L[k][0])
                    visited[L[k][1]-1] = 1
                    visited[L[k][0]-1] = 1
                    room[L[k][0]-1] = L[k][1]
                erase.append(k)
                
            if visit == L[k][0]:
                if visited[L[k][1]-1] == 0:
                    nextvisit[1].append(L[k][1])
                    visited[L[k][0]-1] = 1
                    visited[L[k][1]-1] = 1
                    room[L[k][1]-1] = L[k][0]  
                erase.append(k)

        not_used = list(set(not_used)-set(erase))
    del nextvisit[0]
    
    if len(not_used) == 0:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==2:
    print(1)

Submission status: Time Limit Exceeded

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


def main():
    n, m = map(int, input().split())

    nexts = [[] for i in range(n)]
    
    for _ in range(m):
        ai, bi = map(int, input().split())
        ai -= 1
        bi -= 1
        nexts[ai].append(bi)
        nexts[bi].append(ai)

    blues = [-1] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues
    checked = [0] * n

    red_deque = deque([0])

    while -1 in blues:
        rd = red_deque[0]
        red_deque.popleft()
        if checked[rd] == 0:
            checked[rd] = 1
            for nxt in nexts[rd]:
                if blues[nxt] == -1:
                    blues[nxt] = rd
                    red_deque.append(nxt)

    print("Yes")
    for blue in blues[1:]:
        print(blue + 1)
    

if __name__ == "__main__":
    main()

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,jit
# 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
from networkx import Graph,shortest_path,single_target_shortest_path,astar_path,single_source_dijkstra
G = 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())
rows = [list(map(int,input().split())) for _ in range(M)]

G.add_edges_from(rows)

# shortestPath = shortest_path(G,target=1)
# shortestPath = single_target_shortest_path(G,target=1)
shortestPathLength,shortestPath = single_source_dijkstra(G,source=1)
# print(shortestPath)
if len(shortestPathLength) != N:
    print("No")
    exit()

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


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

Submission status: Time Limit Exceeded

Solution code:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p1 = []
p2 = []
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p1.append(a)
    p2.append(b)
d = [[1], ]
c = [[0], ]
l = 0
flag = True
for j in range(1, n):
    a = []
    b = []
    for i, t in enumerate(p1):
        for h in d[l]:
            if t == h:
                a.append(p2[i])
                b.append(t)
    for i, t in enumerate(p2):
        for h in d[l]:
            if t == h:
                a.append(p1[i])
                b.append(t)
    d.append(a)
    c.append(b)
    if len(d) > l:
        l += 1
    else:
        flag = False
        break
con = []
for i in range(2, n+1):
    for y, j in enumerate(d):
        flfl = True
        for w, k in enumerate(j):
            if k == i:
                con.append(c[y][w])
                flfl=False
                break
        if not flfl:
            break
    if flfl:
        con.append(0)

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

Submission status: Time Limit Exceeded

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


def main():
    n, m = map(int, input().split())

    nexts = [[] for i in range(n)]
    
    for _ in range(m):
        ai, bi = map(int, input().split())
        ai -= 1
        bi -= 1
        nexts[ai].append(bi)
        nexts[bi].append(ai)

    blues = [-1] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues

    red_deque = deque([0])

    while -1 in blues:
        rd = red_deque[0]
        red_deque.popleft()

        for nxt in nexts[rd]:
            if blues[nxt] == -1:
                blues[nxt] = rd
                if nxt not in red_deque:
                    red_deque.append(nxt)

    print("Yes")
    for blue in blues[1:]:
        print(blue + 1)
    

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import queue
INF = float('inf')

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

visited = [INF for _ in range(N)]

q = queue.Queue()
[q.put([x, 0]) for x in graph[0]]
while not q.empty():
    n = q.get()
    nex = n[0]; now = n[1]
    if visited[nex] == INF:
        visited[nex] = now
        [q.put([x, nex]) for x in graph[nex]]

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

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split())
link=[[] for i in range(N)]
for i in range(M):
    A,B=map(int,input().split())
    link[A-1].append(B-1)
    link[B-1].append(A-1)
visited=[False for i in range(N)]
result=[0]*N
Q=[0]
visited[0]=True
while Q:
    v=Q.pop(0)
    for i in link[v]:
        if visited[i]==False:
            visited[i]==True
            result[i]=v
            Q.append(i)
print('Yes')
for i in range(1,N):
    print(result[i]+1)

Submission status: Time Limit Exceeded

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

n = int(s[0])
m = int(s[1])

ld = {}

for i in range(m):
    t = input().split()
    if int(t[0]) in ld:
        ld[int(t[0])].add(int(t[1]))
    else:
        ld[int(t[0])] = {int(t[1])}
    if int(t[1]) in ld:
        ld[int(t[1])].add(int(t[0]))
    else:
        ld[int(t[1])] = {int(t[0])}


if sum(ld.keys()) < int(((n + 1) * n ) / 2):
    print("No")
else:
    s1 = {1}
    s2 = set()
    count = 0
    mydict = {}

    while len(ld) > 0:
        s2.clear()
        for i in ld:
            if len(s1 & ld[i]) != 0:
                #s3 = list(s1 & ld[i])
                mydict.setdefault(i,list(s1 & ld[i])[0])
                s2.add(i)
        for i in s2:
            del ld[i]
        s1 = s2.copy()

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

Submission status: Time Limit Exceeded

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


def main():
    n, m = map(int, input().split())

    nexts = [[] for i in range(n)]
    
    for _ in range(m):
        ai, bi = map(int, input().split())
        ai -= 1
        bi -= 1
        nexts[ai].append(bi)
        nexts[bi].append(ai)

    blues = [1] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues

    red_deque = deque([0])

    arrows = [0] * n

    while 1 in blues:
        rd = red_deque[0]
        red_deque.popleft()

        for nxt in nexts[rd]:
            if blues[nxt] == 1:
                blues[nxt] = 0
                if nxt not in red_deque:
                    red_deque.append(nxt)
                arrows[nxt] = rd

    print("Yes")
    for arrow in arrows[1:]:
        print(arrow + 1)
    

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque

input = stdin.readline


def main():
    n, m = map(int, input().split())

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

    blues = [1] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues

    red_deque = deque([0])

    arrows = [0] * n

    while 1 in blues:
        rd = red_deque[0]
        red_deque.popleft()

        for nxt in nexts[rd]:
            if blues[nxt] == 1:
                blues[nxt] = 0
                if rd not in red_deque:
                    red_deque.append(nxt)
                arrows[nxt] = rd

    print("Yes")
    for arrow in arrows[1:]:
        print(arrow + 1)
    

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
from pprint import pprint

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

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

# 道の接続マップ
route2 = {}

# 接続している部屋のマップ
room_next = [[] for n in range(N)]

for a, b in zip(A, B):
    room_next[a - 1].append(b - 1)
    room_next[b - 1].append(a - 1)

# pprint(room_next)

# route2.update({(a - 1, b - 1): True})
# route2.update({(b - 1, a - 1): True})

# 探索する
room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

# 次に行く部屋
stack = [0]

while stack:
    now = stack.pop()
    for j in room_next[now]:
        # if (now, j) in route2.keys():
        if room_depth[j] is None or room_depth[j] > room_depth[now] + 1:
            room_depth[j] = room_depth[now] + 1
            room_sign[j] = now + 1
            stack.append(j)

print('Yes')
for s in room_sign[1:]:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
a=[]
b=[]
for i in range(M):
    aa,bb = map(int, input().split())
    a.append(aa)
    b.append(bb)

michishirube=[0]*N
li=[]
li.append(1)
for i in range(N):
     for j in range(M):
         if li[i]==a[j] and not b[j] in li:
             li.append(b[j])
             michishirube[b[j]-1]=li[i]

         elif li[i]==b[j] and not a[j] in li:
             li.append(a[j])
             michishirube[a[j]-1]=li[i]
         if len(li)==N:
             break

if len(li)<N:
    print("No")

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

Submission status: Time Limit Exceeded

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[0 for k in range(N)]
visited[0]=1
not_used = [k for k in range(M)]
for j in range(M-1):
    for visit in nextvisit[j]:
        """
        print("L=",L)
        print("next=",nextvisit[j])
        print("not_used", not_used)
        """
        erase = []
        for k in not_used:
            if visit == L[k][1]:
                if visited[L[k][0]-1] == 0:
                    nextvisit[j+1].append(L[k][0])
                    visited[L[k][1]-1] = 1
                    visited[L[k][0]-1] = 1
                    room[L[k][0]-1] = L[k][1]
                erase.append(k)
                
            if visit == L[k][0]:
                if visited[L[k][1]-1] == 0:
                    nextvisit[j+1].append(L[k][1])
                    visited[L[k][0]-1] = 1
                    visited[L[k][1]-1] = 1
                    room[L[k][1]-1] = L[k][0]  
                erase.append(k)    
            not_used = list(set(not_used)-set(erase))
    
    if len(not_used) == 0:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==2:
    print(1)

Submission status: Time Limit Exceeded

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

n = int(s[0])
m = int(s[1])

sl = set()
ld = {}

s1 = {1}
s2 = set()


for i in range(m):
    t = input().split()
    sl.add(int(t[0]))
    sl.add(int(t[1]))
    if int(t[0]) in ld:
        ld[int(t[0])].add(int(t[1]))
    else:
        ld[int(t[0])] = {int(t[1])}
    if int(t[1]) in ld:
        ld[int(t[1])].add(int(t[0]))
    else:
        ld[int(t[1])] = {int(t[0])}


if sum(sl) < int(((n + 1) * n ) / 2):
    print("No")
else:
    count = 0
    mydict = {}

    while len(ld) > 0:
        s2.clear()
        for i in ld:
            if len(s1 & ld[i]) != 0:
                #s3 = list(s1 & ld[i])
                mydict.setdefault(i,list(s1 & ld[i])[0])
                s2.add(i)
        for i in s2:
            del ld[i]
        s1 = s2.copy()

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

Submission status: Time Limit Exceeded

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append(set([a,b]))

output = [0] + [0] + [BigM]*(N-1)
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    for e in E:
        if n in e:
            next = list(e - set([n]))[0]
            if output[next] == BigM:
                output[next] = n
                now.append(int(next))

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Time Limit Exceeded

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


def main():
    n, m = map(int, input().split())

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

    blues = [1] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues
    reds = [0] * n
    reds[0] = 1
    new_reds = [0] * n

    arrows = [0] * n

    while 1 in blues:
        for i in range(n):
            if reds[i] == 1:
                for nxt in nexts[i]:
                    if blues[nxt] == 1:
                        blues[nxt] = 0
                        new_reds[nxt] = 1
                        arrows[nxt] = i

        reds = new_reds
        new_reds = [0] * n
    
    print("Yes")
    for arrow in arrows[1:]:
        print(arrow + 1)
    

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# = int(input())
N, M = map(int, input().split())
# = list(map(int, input().split()))
# = [int(input()) for i in range(N)]
AB = [list(map(int, input().split())) for i in range(M)]
sign = [0]*N
queue = []
graph = []
sign[0] = 1

for i in range(1, N+1):
    List = []
    for j in range(M):
        if AB[j][0] == i:
            List.append(AB[j][1])
        elif AB[j][1] == i:
            List.append(AB[j][0])
    graph.append(List)

for number in graph[0]:
    queue.append(number)
    sign[number-1] = 1

for i in range(1, N):
    for j in range(len(graph[queue[0]-1])):
        if sign[graph[queue[0]-1][j]-1] == 0:
            sign[graph[queue[0]-1][j]-1] = queue[0]
            queue.append(graph[queue[0]-1][j])
    queue.pop(0)

sign.pop(0)

if sign.count(0) > 0:
    print("No")
else:
    print("Yes")
    for number in sign:
        print(number)

Submission status: Time Limit Exceeded

Solution code:
nm = input().split()
n = int(nm[0])
m = int(nm[1])

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

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

visited = [0]
output = [0]*n
shortest = [0]
while len(visited) < n:
    for i in range(len(shortest)):
        for j in range(len(roads[shortest[i]])):
            if roads[shortest[i]][j] not in visited:
                visited.append(roads[shortest[i]][j])
                shortest.append(roads[shortest[i]][j])
                output[roads[shortest[i]][j]] = shortest[i]

print('Yes')
for i in range(1, len(output)):
    print(output[i]+1)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == "__main__":
    n, m = map(int, input().split())

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


    red_set = [0]
    new_red_set = []
    #blue_set = [x + 1 for x in range(n - 1)]
    #new_blue_set = blue_set
    blues = [1] * n # 1 is in blues
    blues[0] = 0 # 0 is not in blues
    reds = [0] * n
    reds[0] = 1
    new_reds = [0] * n

    arrows = [0] * n

    while 1 in blues:
        for i in range(n):
            if reds[i] == 1:
                for nxt in nexts[i]:
                    if blues[nxt] == 1:
                        blues[nxt] = 0
                        new_reds[nxt] = 1
                        arrows[nxt] = i

        reds = new_reds
        new_reds = [0] * n
    
    print("Yes")
    for arrow in arrows[1:]:
        print(arrow + 1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque
from heapq import heappush, heappop


class BreadthFirstSearch:
    def __init__(self, num_nodes):
        self.n = num_nodes
        self.adj_list = [[] for _ in range(self.n)]

    # Edge数分回すことを想定
    def add_edge(self, start, end, undirected=True):
        self.adj_list[start].append(end)
        if undirected:
            self.adj_list[end].append(start)

    # depth = distance
    def search(self, start_node):
        order = [-1] * self.n  # a bfs ordering of each vertex
        parent = [-1] * self.n  # parent of each vertex in the bfs search tree
        depth = [-1] * self.n  # the depth of each vertex
        q = deque([(start_node, -1, 0)])  # (vertex, parent, depth)
        num = 0  # current ordering
        while len(q) > 0:
            v, p, d = q.popleft()
            if order[v] < 0:  # visited v for the first time
                order[v] = num
                parent[v] = p
                depth[v] = d
                num += 1
                for u in self.adj_list[v]:
                    if order[u] >= 0:
                        continue
                    q.append((u, v, d+1))
        return order, parent, depth


class Dijkstra:
    def __init__(self, num_nodes):
        self.n = num_nodes
        self.adj_list = [[] for _ in range(self.n)]

    # Edge数分回すことを想定
    def add_edge(self, start, end, weight=1, undirected=False):
        self.adj_list[start].append((end, weight))
        if undirected:
            self.adj_list[end].append((start, weight))

    def distance(self, start):
        # 始点から各頂点までの最短距離を格納する
        self.dist = [float('inf') for _ in range(self.n)]
        # 最短経路における, その頂点の前の頂点のIDを格納する
        self.prev = [-1 for _ in range(self.n)]
        self.dist[start] = 0
        # 各要素は，(頂点vのID, startからある頂点vまでの仮の距離)からなるタプル
        q = []
        heappush(q, (start, 0))
        while len(q) != 0:
            src, prov_cost = heappop(q)
            # プライオリティキューに格納されている最短距離が, 現在計算できている最短距離より大きければ，distの更新をする必要はない
            if self.dist[src] < prov_cost:
                continue
            # 他の頂点の探索
            for val in self.adj_list[src]:
                dest, cost = val
                if self.dist[dest] > self.dist[src] + cost:
                    self.dist[dest] = self.dist[src] + cost  # distの更新
                    heappush(q, (dest, self.dist[dest]))  # キューに新たな仮の距離の情報をpush
                    self.prev[dest] = src
        return self.dist, self.prev

    def shortest_path(self, goal):
        path = [goal]
        dest = goal
        # 終点から最短経路を逆順に辿る
        while self.prev[dest] != float('inf'):
            if self.prev[dest] == -1:
                break
            path.append(self.prev[dest])
            dest = self.prev[dest]
        return path[::-1]


def get_result(data):
    N, M = data[0]
    A = data[1:]
    solver = Dijkstra(N)
    for val in A:
        solver.add_edge(val[0]-1, val[1]-1, undirected=True)
    _, prev = solver.distance(0)
    print('Yes')
    for p in prev[1:]:
        print(p + 1)
    return None


# def get_result(data):
#     N, M = data[0]
#     A = data[1:]
#     solver = BreadthFirstSearch(N)
#     for val in A:
#         solver.add_edge(val[0]-1, val[1]-1)
#     _, parent, _ = solver.search(0)
#     print('Yes')
#     for p in parent[1:]:
#         print(p+1)
#     return None


if __name__ == '__main__':
    raw_data = [val.rstrip() for val in stdin.readlines()]
    data = [list(map(int, val.split(' '))) for val in raw_data]
    get_result(data)
    # print(result)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
input = sys.stdin.readline
N, M = map(int, input().split())
g = defaultdict(list)
for i in range(M):
  a, b = map(int, input().split())
  g[a].append(b)
  g[b].append(a)
ans = [0 for _ in range(N+1)]
ans[1] = 1
#print(g)
current = [1]
while 0 in ans[2:]:
  #print(ans)
  next = []
  for i in current:
    #print('i',i)
    for j in g[i]:
      if ans[j] == 0:
        ans[j] = i
        next.append(j)
  current = next
print('Yes')
for i in range(2,N+1):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
if __name__ == "__main__":
    n, m = map(int, input().split())

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


    red_set = [0]
    new_red_set = []
    #blue_set = [x + 1 for x in range(n - 1)]
    #new_blue_set = blue_set
    blues = [1 for i in range(n)] # 1 is in blues
    blues[0] = 0 # 0 is not in blues
    reds = [0 for _ in range(n)]
    reds[0] = 1
    new_reds = [0 for _ in range(n)]

    arrows = [0] * n

    while 1 in blues:
        for i in range(n):
            if reds[i] == 1:
                for nxt in nexts[i]:
                    if blues[nxt] == 1:
                        blues[nxt] = 0
                        new_reds[nxt] = 1
                        arrows[nxt] = i

        reds = new_reds
        new_reds = [0 for _ in range(n)]
    
    print("Yes")
    for arrow in arrows[1:]:
        print(arrow + 1)