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 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 = [10**15 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 (dest, cost) in self.adj_list[src]:
                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 i in range(1, N):
        print(prev[i] + 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:
s = input().split()

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

#ll = [set() for j in range(n + 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]))
    #ll[int(t[0])].add(int(t[1]))
    #ll[int(t[1])].add(int(t[0]))
    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 = {}
    out = 0

    while count < n:
        s2.clear()
        for i in ld:
            if len(s1 & ld[i]) != 0:
                s3 = list(s1 & ld[i])
                mydict.setdefault(i,s3[0])
                s2.add(i)
                count += 1
        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
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 = [10**15 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 (dest, cost) in self.adj_list[src]:
                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:
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 = [0 for i in range(n)] # 0 is unceked
    blues[0] = 1 # 1 is checked

    arrows = [0] * n

    while 0 in blues:
        for r in red_set:
            for nxt in nexts[r]:
                if blues[nxt] == 0:
                    blues[nxt] = 1
                    if nxt not in new_red_set:
                        new_red_set.append(nxt)
                    arrows[nxt] = r

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

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)]
#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:
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 (dest, cost) in self.adj_list[src]:
                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)
    _ = solver.distance(0)
    print('Yes')
    for p in solver.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 numpy as np
n,m = map(int, input().split())

routes = []
for i in range(m):
    route = list(map(int, input().split()))
    routes.append(route)
    routes[i] = routes[i] - np.ones(2) #道の番号をずらす

rooms = np.zeros(n) # 行ってない部屋は0、行った部屋は1
marks = np.zeros(n) # 部屋におく道標
roomsrate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1

turn = 0
for i in roomsrate:
    newrate = []
    for j in roomsrate[turn]: #turn回目に行ける部屋を調べる
        for k in range(m):
            a = int(routes[k][0])
            b = int(routes[k][1]) 
            if (j == a and int(rooms[b]) == 0):
                rooms[b] = 1
                marks[b] = a
                newrate.append(b)
            elif (j == b and int(rooms[a]) == 0):
                rooms[a] = 1
                marks[a] = b
                newrate.append(a)
    roomsrate.append(newrate)
    if (len(newrate) == 0):
        break
    turn = turn + 1

if(np.all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
## ---- DFS
class Node(object):
    def __init__(self, name):
        self.name = name
    def getName(self):
        return self.name
    def __str__(self):
        return self.name
    
class Edge(object):
    def __init__(self, src, dest):
        self.src = src
        self.dest = dest
    def getSource(self):
        return self.src
    def getDestination(self):
        return self.dest
    def __str__(self):
        return self.src.getName() + '->' + self.dest.getName()
    
class WeightedEdje(Edge):
    def __init__(sekf, src, dest, weight=1.0):
        self.src = scr
        self.dest = dest
        self.weight = weight
    def getWeight(self):
        return self.weight
    def __str__(self):
        return self.src.getName() + '->(' + str(self.weight) + ')' + self.dest.getName()

class Digraph(object):
    def __init__(self):
        self.nodes = []
        self.edges = {}
    def addNode(self, node):
        if node in self.nodes:
            raise ValueError('Duplicate node')
        else:
            self.nodes.append(node)
            self.edges[node] = []
    def addEdge(self, edge):
        src = edge.getSource()
        dest = edge.getDestination()
        if not (src in self.nodes and dest in self.nodes):
            raise ValueError('node not in graph')
        self.edges[src].append(dest)
    def childrenOf(self, node):
        return self.edges[node]
    def hasNode(self, node):
        return node in self.nodes
    def __str__(self):
        result=''
        for src in self.nodes:
            for dest in self.nodes:
                result = result + src.getName() + '->' + dest.getName() + '\n'
        return result[:-1]
            
class Graph(Digraph):
    def addEdge(self, edge):
        addEdge(self, edge)
        Digraph.addEdge(self, edge)
        rev  = Edge(edge.getDestination(), edge.getSorce())
        Digraph.addEdge(self, rev)

def DFS(graph,start,end,path,shortest):
    path = path + [start]
    if start == end:
        return path
    for node in graph.childrenOf(start):
        if node not in path:
            if shortest == None or len(path) < len(shortest):
                newPath = DFS(graph, node, end, path, shortest)
                if newPath != None:
                    shortest = newPath
    return shortest

def shortestPath(graph, start, end):
    return DFS(graph, start, end, [], None)

## ----main
N, M = list(map(int,input().split()))

g = Digraph()
for n in range(1,N+1):
    g.addNode(n)

for _ in range(M):
    a,b = list(map(int,input().split()))
    g.addEdge(Edge(a,b))
    g.addEdge(Edge(b,a))


err = False
rets = [0] * (N+1)
for i in range(2,N+1):
    if i not in rets:
        sp = shortestPath(g,i,1)
        if len(sp) == 0:
            err = True
            break
        for i in range(len(sp)-1):
            rets[sp[i]] = sp[i+1]

if err == False:
    print("Yes")
    for i in range(2,N+1):
        print(rets[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import math
 
nm = list(map(int,input().split()))
N, M = nm[0], nm[1]

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


# 道のソート (不要？)
#
#for i in range(M):
#  if( AB[i][0] > AB[i][1] ):
#    AB[i][0], AB[i][1] = AB[i][1], AB[i][0]
#
#for i in range(M-1):
#  for j in range(M-1-i):
#    if( AB[j][0] > AB[j+1][0] ):
#      temp = AB[j]
#      AB[j] = AB[j+1]
#      AB[j+1] = temp
#    if( AB[j][0] == AB[j+1][0] and AB[j][1] > AB[j+1][1] ):
#      temp = AB[j]
#      AB[j] = AB[j+1]
#      AB[j+1] = temp
#  
#print(AB)


# 各部屋から"部屋1"までの最短距離をtierとする。
# [0],[1]は初期値0、[2]~[N]を初期値-1とする。
# -1がある場合、目標は達成不可 → 答えは"No"となる。
tier = [0]*2+[-1]*(N-1)

# 各部屋に設置する、道しるべが指す先の部屋の番号
guide = [0]*2+[-1]*(N-1)


root = [1] # まず、入口に最も近い"部屋1"を最初の探索に用いる

for t in range(1, 2*(10**5) ):
  
  for r in range( len(root) ):
    for i in range(M):
      if ( AB[i][0] == root[r] ):
        if( tier[ AB[i][1] ] == -1 or tier[ AB[i][1] ] > t ):
          tier[ AB[i][1] ] = t
          guide[ AB[i][1] ] = AB[i][0]
          
      elif ( AB[i][1] == root[r] ):
        if( tier[ AB[i][0] ] == -1 or tier[ AB[i][0] ] > t ):
          tier[ AB[i][0] ] = t
          guide[ AB[i][0] ] = AB[i][1]
          
  root = [] # 次回の探索に用いる部屋を保存
  for i in range(2,N+1):
    if( tier[i] == t ):
      root.append( i )
  #print(tier)
  #print("tier.{0}: {1}".format(t, root) )
  
  if( root==[] ): # 1つのtierに部屋が一つもない場合、探索終了。
    tier_max = t-1
    break

#print("tier_max : {0}".format(tier_max) )
#print("tier : {0}".format(tier) )
#print("guide: {0}".format(guide) )

#

ans = 1
# リストtierに-1がある場合、目標達成は不可となる
for i in range(2,N+1):
  if ( tier[i] == -1 ):
    ans = 0

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

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
n,m=map(int,input().split())
s=[list(map(int,input().split())) for i in range(m)]

g=nx.Graph()
g.add_nodes_from([i for i in range(1,n+1)])

for x in s:
    g.add_edge(x[0],x[1])
di=nx.dijkstra_predecessor_and_distance(g,source=1)

if len(di[0])!=n:
    print("No")
    exit()

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

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

    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)
    _ = solver.distance(0)
    print('Yes')
    prev = solver.prev[1:]
    for p in prev:
        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 numpy as np
# import copy
import queue


q = queue.Queue()

n, m = map(int, input().split())
l = [[0 for _ in range(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


# l = np.array(l)
# lc = copy.deepcopy(l)
li = [-1 for _ in range(n)]

def search(x):
    if sum(l[x]) == 0:
        q.queue = False
        return
    
#     ind_lis = np.where(lc[x] == 1)[0]
#     ind_lis = [e for e in ind_lis if li[e] == -1]
#     print(li)
#     print(lc[x])
    for i,e in enumerate(l[x]):
#         print(i,e)
        if li[i] != -1 or e == 0:
            continue
        li[i] = x
#         print('q', i+1)
        q.put(i)
x = 0
search(x)
while q.queue:
    search(q.get())

if li[1:].count(-1) == 0:
    print('Yes')
    for e in li[1:]:
        print(e+1)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m = map(int, input().split())

routes = []
for i in range(m):
    route = list(map(int, input().split()))
    routes.append(route)

for i in range(m):
    routes[i] = routes[i] - np.ones(2) #道の番号をずらす

rooms = np.zeros(n) # 行ってない部屋は0、行った部屋は1
marks = np.zeros(n) # 部屋におく道標
roomsrate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1
marks[0] = 1

turn = 0
for i in roomsrate:
    newrate = []
    for j in roomsrate[turn]: #turn回目に行ける部屋を調べる
        for k in range(m):
            a = int(routes[k][0])
            b = int(routes[k][1]) 
            if (j == a or j == b):
                if (int(rooms[b]) == 0):
                    rooms[b] = 1
                    marks[b] = a
                    newrate.append(b)
                elif (int(rooms[a]) == 0):
                    rooms[a] = 1
                    marks[a] = b
                    newrate.append(a)
    roomsrate.append(newrate)
    if (len(newrate) == 0):
        break
    turn = turn + 1

if(np.all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

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

    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)
    _ = solver.distance(0)
    print('Yes')
    for p in solver.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)