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:
# -*- coding: utf-8 -*-

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())

C = [1]
C_old = [0]
D = list(range(M))
D_old=[0]*M
E = [0]*N
F = [0]*N
#print("{}".format(D))
for i in range(N):
    if not 0 in F[1:N]:
        break
    #print("{}".format(i))
    C_old=[0]
    #print("{}".format(C))
    #print("{}".format(D))
    for j in D:
        #print("A={},B={},j={}".format(A[j],B[j],j))
        if A[j] in C:
            C_old.append(B[j])
            if E[B[j]-1]==0:
                E[B[j]-1]=A[j]
                F[B[j]-1]=1
                D_old[j]=1
             #else:
            #     E[B[j]-1]=min(A[j],E[B[j]-1])
            #print("D={}".format(D))
            #print("{}".format(E))

        elif B[j] in C:
             C_old.append(A[j])
             if E[A[j]-1]==0:
                 E[A[j]-1]=B[j]
                 F[A[j]-1]=1
                 D_old[j]=1
             #else:
            #     E[A[j]-1]=min(B[j],E[A[j]-1])
             #print("D={}".format(D))
             #print("{}".format(E))

    C.extend(C_old)
    D=[i for i in D if D_old[i]== 0]


if not 0 in F[1:N]:
    print("Yes")
    for i in range(N-1):
        print("{}".format(E[i+1]))

else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import math
import queue
def dijkstra(n, w):
    ans=[math.inf]*n
    done=[]
    done.append(1)
    q=queue.Queue()
    for i in range(n+1):
        if w[1][i]==1:
            q.put(i)
            ans[i-1]=1
            done.append(i)
    while not q.empty():
        now=q.get()
        for i in range(n+1):
            if w[now][i]==1 and (i not in done):
                q.put(i)
                done.append(i)
                ans[i-1]=now
        if max(ans)!=math.inf:
            break
    return ans


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

for i in range(m):
    s = list(map(int, input().split()))
    mapping[s[0]][s[1]]=1
    mapping[s[1]][s[0]] = 1

ans=dijkstra(n,mapping)
if not math.inf in ans[1:]:
    print('Yes')
    for i in ans[1:]:
        print(i)
else:
    print('No')

Submission status: Time Limit Exceeded

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

    edges = [[] for _ in range(n)]

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

    q = [0]

    ans = [-1]*n
    ans[0] = 0
    count = 1

    while q:
        l = q.pop(0)
        for i in edges[l]:
            if ans[i] == -1:
                ans[i] = l
                count += 1
                q.append(i)
        if count == n:
            break

    if count == n:
        print('Yes')
        for i in ans[1:]:
            print(i+1)
    else:
        print('No')

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M = map(int, input().split())
graph = [set() for _ in range(N+1)]
for i in range(M):
    a, b = map(int, input().split())
    graph[a].add(b)
    graph[b].add(a)

def bfs(graph):
    visited = set()
    queue = deque()
    queue.append(1)
    ans = [0] * (N+1)
    while queue:
        cur = queue.popleft()
        visited.add(cur)
        for n in graph[cur]:
            if n not in visited and n not in queue:
                ans[n] = cur
                queue.append(n)
    return ans

ans = bfs(graph)
print("Yes")
for i in range(2, len(ans)):
    print(ans[i])

Submission status: Time Limit Exceeded

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

edges = [[] for _ in range(n)]

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

q = [0]

ans = [-1]*n
ans[0] = 0
count = 1

while q:
    l = q.pop(0)
    for i in edges[l]:
        if ans[i] == -1:
            ans[i] = l
            count += 1
            q.append(i)
    if count == n:
        break

if count == n:
    print('Yes')
    for i in ans[1:]:
        print(i+1)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:

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

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

    stack = []
    connected_to_one = [*connections[0]]

    for room in connected_to_one:
        ans[room] = 1

        connections[0].remove(room)
        connections[room].remove(0)

        stack.append(room)

    while len(stack) > 0:
        next_stack = []

        for room in stack:
            connected = [*connections[room]]

            for _room in connected:
                if ans[_room] == -1:
                    ans[_room] = room + 1

                    connections[_room].remove(room)
                    connections[room].remove(_room)

                    next_stack.append(_room)

        stack = [*next_stack]

    _ans = ans[1:]

    if -1 in _ans:
        print('No')
    else:
        print('Yes')
        for i in _ans:
            print(i)
            
resolve()

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int, input().split(" "))
route = []
for i in range(m):
    route.append(list(map(int, input().split(" "))))
answer = [-1 for i in range(n + 1)]
answer[0], answer[1] = 0, 0
chokuzen = [1]
while(True):
    if not -1 in answer:
        print('Yes')
        for i in range(2, n + 1):
            print(answer[i])
        break
    temp = []
    tsuika = True
    for i in range(m):
        if route[i][0] in chokuzen and answer[route[i][1]] == -1:
            tsuika = False
            temp.append(route[i][1])
            answer[route[i][1]] = route[i][0]
        elif route[i][1] in chokuzen and answer[route[i][0]] == -1:
            tsuika = False
            temp.append(route[i][0])
            answer[route[i][0]] = route[i][1]
    if tsuika:
        print('No')
        break
    chokuzen = temp

Submission status: Time Limit Exceeded

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

N = int(N)
M = int(M)

neighbor_dict = {}
michisirube_dict = {}

for i in range(N):
	neighbor_dict[i+1] = []
	michisirube_dict[i+1] = None

for i in range(M):

	A, B = input().split(" ")
	A = int(A)
	B = int(B)
	neighbor_dict[A].append(B)
	neighbor_dict[B].append(A)


def set_michisirube(rooms):
	nexts = []
	for room in rooms:
		for next_room in neighbor_dict[room]:
			if michisirube_dict[next_room] is None:
				michisirube_dict[next_room] = room
				nexts.append(next_room)
			else:
				pass
		
	return nexts



nexts = set_michisirube([1,])
comp = False

while comp == False:
	nexts = set_michisirube(nexts)
	if None in list(michisirube_dict.values()):
		pass
	else:
		comp = True


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

Submission status: Time Limit Exceeded

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

N = int(N)
M = int(M)

neighbor_dict = {}
michisirube_dict = {}

for i in range(N):
	neighbor_dict[i+1] = []
	michisirube_dict[i+1] = None

for i in range(M):

	A, B = input().split(" ")
	A = int(A)
	B = int(B)
	neighbor_dict[A].append(B)
	neighbor_dict[B].append(A)


def set_michisirube(rooms):
	done = []
	for room in rooms:
		for next_room in neighbor_dict[room]:
			if michisirube_dict[next_room] is None:
				michisirube_dict[next_room] = room
			else:
				pass
		done.append(room)
		
	return done



done = set_michisirube([1,])
comp = False

while comp == False:
	nexts = []
	for room in done:
		nexts += neighbor_dict[room]
	nexts = list(set(nexts))
	done = set_michisirube(nexts)
	if None in list(michisirube_dict.values()):
		pass
	else:
		comp = True


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

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
edg=[[] for i in range(n)]
for i in range(m):
    a,b=map(int,input().split())
    a-=1;b-=1
    edg[a].append(b)
    edg[b].append(a)
visited=[False for i in range(n)]
visited[0]=True
parent=[None for i in range(n)]
st=[0]
while st!=[]:
    now=st[0]
    del(st[0])
    for i in edg[now]:
        if not visited[i]:
            st.append(i)
            visited[i]=True
            parent[i]=now
print("Yes")
for i in parent[1:]:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
import queue

N, M = [int(x) for x in input().split(' ')]
A = []
B = []
connected = [set() for _ in range(N)]
for _ in range(M):
  a, b = [int(x) - 1 for x in input().split(' ')]
  A.append(a)
  B.append(b)
  connected[a].add(b)
  connected[b].add(a)
  

print('Yes')

ans = [-1] * N
dist = [N+100] * N
dist[0] = 0
next_all = queue.Queue(N)
next_all.put(0)
processed = set()

while not next_all.empty():
  n = next_all.get()
  processed.add(n)
  
  pre = min([(dist[c], c) for c in connected[n]])
  dist[n] = pre[0] + 1 if pre[0] < N else 0
  ans[n] = pre[1]
  for c in connected[n]:
    if c not in processed:
      next_all.put(c)
# print(dist)
for a in ans[1:]:
  print(a+1)

Submission status: Time Limit Exceeded

Solution code:
import queue

N, M = [int(x) for x in input().split(' ')]
A = []
B = []
connected = [set() for _ in range(N)]
for _ in range(M):
  a, b = [int(x) - 1 for x in input().split(' ')]
  A.append(a)
  B.append(b)
  connected[a].add(b)
  connected[b].add(a)
  

print('Yes')

ans = [-1] * N
dist = [N+100] * N
dist[0] = 0
next_all = queue.Queue(N)
next_all.put(0)

while not next_all.empty():
  n = next_all.get()
  # print(n, dist, ans)
  if ans[n] >= 0:
    continue
  pre = min([(dist[c], c) for c in connected[n]])
  dist[n] = pre[0] + 1 if pre[0] < N else 0
  ans[n] = pre[1]
  for c in connected[n]:
    if ans[c] < 0:
      next_all.put(c)
# print(dist)
for a in ans[1:]:
  print(a+1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections import defaultdict
sys.setrecursionlimit(10**8)
INF = float("inf")
import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):

    c = np.ones(M)
    edge = csr_matrix((c, (A, B)), (N+1, N+1))
    forward_dist, pred = dijkstra(
        edge, indices=1,
        return_predecessors=True, directed=False,
        unweighted=True)

    if (pred[2:] == -9999).any():
        print("No")
    else:
        print("Yes")
        for value in pred[2:]:
            print(value)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=map(int,input().split())
AB = [list(map(int, input().split())) for _ in range(M)]
l=[0]*(N-1)
bo=[1]
box=deque(bo)
count=0
while count<N-1:
    for i in range(M):
        if AB[i][0]==box[0] and l[AB[i][1]-2]==0:
            box.append(AB[i][1])
            l[AB[i][1]-2]=AB[i][0]
            count+=1
        elif AB[i][1]==box[0] and l[AB[i][0]-2]==0:
            box.append(AB[i][0])
            l[AB[i][0]-2]=AB[i][1]
            count+=1
    box.popleft()
print("Yes")
[print(i) for i in l]

Submission status: Time Limit Exceeded

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

root = [[] for i in range(n)]
for _ in range(m):
    a, b = (int(x) for x in input().split())
    root[b-1].append(a-1)
    root[a-1].append(b-1) 

stack=[0]
check = [-1]*n
check[0] = 0

while len(stack)>0:
    v = stack.pop(0)
    for i in root[v]:
        if check[i] == -1:
            check[i]=v+1
            stack.append(i)


print('Yes')
for i in range(1,n):
    print(check[i])

Submission status: Time Limit Exceeded

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

root = [[] for i in range(n)]
for _ in range(m):
    a, b = (int(x) for x in input().split())
    root[b-1].append(a-1)
    root[a-1].append(b-1) 

stack=[0]
check = [-1]*n
check[0] = 0

while len(stack)>0:
    v = stack.pop(0)
    for i in root[v]:
        if check[i] == -1:
            check[i]=v+1
            stack.append(i)

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

Submission status: Time Limit Exceeded

Solution code:

N, M = map(int, input().split())
AB = [list(map(int, input().split())) for i in range(M)]
P = [0] * N
Q = [1]
n = N - 1
while n > 0:
    for q in Q:
        for i in range(M):
            if AB[i][0] == q:
                if P[AB[i][1] - 1] == 0:
                    P[AB[i][1] - 1] = q
                    Q.append(AB[i][1])
                    AB[i] = [0, 0]
                    n -= 1
            elif AB[i][1] == q:
                if P[AB[i][0] - 1] == 0:
                    P[AB[i][0] - 1] = q
                    Q.append(AB[i][0])
                    AB[i] = [0, 0]
                    n -= 1
print('Yes')
for i in range(1, N):
    print(P[i])

Submission status: Time Limit Exceeded

Solution code:
import heapq
from collections import deque
class Graph:
    def __init__(self,v,edgelist,w_v = None,directed = False):
        super().__init__()
        self.v = v
        self.w_e = [{} for _ in [0]*self.v]
        self.neighbor = [[] for _ in [0]*self.v]
        self.w_v = w_v
        self.directed = directed

        for i,j,w in edgelist:
            self.w_e[i][j] = w
            self.neighbor[i].append(j)

    def dijkstra(self,v_n):
        d = [float('inf')]*self.v
        d[v_n] = 0
        prev = [-1]*self.v

        queue = []
        for i,d_i in enumerate(d): heapq.heappush(queue,(d_i,i))
        
        while len(queue)>0:
            d_u,u = queue.pop()
            if d[u]<d_u :continue
            for v in self.neighbor[u]:
                alt = d[u]+self.w_e[u][v]
                if d[v]>alt:
                    d[v] = alt
                    prev[v] = u
                    heapq.heappush(queue,(alt,v))

        return d,prev

    def warshallFloyd(self):
        d = [[10**18]*self.v for _ in [0]*self.v]
        for i in range(self.v):
            d[i][i] = 0
            
        for i in range(self.v):
            for j in self.neighbor[i]:
                d[i][j] = self.w_e[i][j]
            
        for i in range(self.v):
            for j in self.neighbor[i]:
                d[i][j] = self.w_e[i][j]
        
        for k in range(self.v):
            for i in range(self.v):
                for j in range(self.v):
                    check = d[i][k] + d[k][j]
                    if d[i][j] > check:
                        d[i][j] = check
        return d

    def prim(self):
        gb = GraphBuilder(self.v,self.directed)

        queue = []
        for i,w in self.w_e[0].items(): heapq.heappush(queue,(w,0,i))
        rest = [True]*self.v
        rest[0] = False

        while len(queue)>0:
            w,i,j = heapq.heappop(queue)
            if rest[j]:
                gb.addEdge(i,j,w)
                rest[j] = False
                for k,w in self.w_e[j].items():
                    if rest[k]:
                        heapq.heappush(queue,(w,j,k))

        return gb

    def bfs(self,vartex = 0):
        todo = [True]*self.v
        queue = deque([vartex])
        while(len(queue)>0):
            v = queue.popleft
            todo[v] = False
            yield v
            for v_i in self.neighbor[v]:
                if todo[v_i]:
                    queue.append(v_i)

    def dfs(self,vartex = 0):
        seen = [False]*self.v
        def recdfs(v):
            seen[vartex] = True
            for next_v in self.neighbor[vartex]:
                if (seen[next_v]):continue
                recdfs(next_v)
            
class Tree():
    def __init__(self,v,e):
        pass

class GraphBuilder():
    def __init__(self,v,directed = False,edge = None, weights = None):
        self.v = v
        self.directed = directed
        self.edge = []
        self.weights = []
        if edge is not None:
            self.addEdges(edge)
        if weights is not None:
            self.addVartex(weights)

    def addEdge(self,i,j,w=1):
        if not self.directed:
            self.edge.append((j,i,w))
        self.edge.append((i,j,w))

    def addEdges(self,edgelist,weight = True):
        if weight:
            if self.directed:
                for i,j,w in edgelist:
                    self.edge.append((i,j,w))
            else:
                for i,j,w in edgelist:
                    self.edge.append((i,j,w))
                    self.edge.append((j,i,w))
        else:
            if self.directed:
                for i,j in edgelist:
                    self.edge.append((i,j,1))
            else:
                for i,j in edgelist:
                    self.edge.append((i,j,1))
                    self.edge.append((j,i,1))
    
    def addVartex(self,weights):
        if len(weights) != self.v:
            return
        self.weights.extend(weights)

    def addAdjMat(self, mat):
        for i,mat_i in enumerate(mat):
            for j,w in enumerate(mat_i):
                self.edge.append((i,j,w))

    def buildTree(self):
        pass

    def buildGraph(self):
        return Graph(self.v,self.edge,directed=self.directed)

def main():
    n,m = tuple([int(t)for t in input().split()])
    edge = []
 
    for i in range(m):
        a,b = tuple([int(t)for t in input().split()])
        edge.append((a-1,b-1,1))
    
    gb = GraphBuilder(n,edge=edge)
    g = gb.buildGraph()
    
    print("Yes")
    ans = g.dijkstra(0)[1]
    for a_i in ans[1:]:
      print(a_i+1)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
mNM = map(int, input().split())
lNM = list(mNM)

mWay = [map(int, input().split()) for i in range(lNM[1])]
lWay = [list(mWay[i]) for i in range(lNM[1])]

maps = [-1 for i in range(lNM[0])]
deep = [-1 for i in range(lNM[0])]
ways = [[] for i in range(lNM[0])]

for i in range(lNM[1]):
    ways[lWay[i][0] - 1].append(lWay[i][1])
    ways[lWay[i][1] - 1].append(lWay[i][0])

maps[0] = 0
deep[0] = 0

for i in range(lNM[0]):
    try:
        index = [n for n, v in enumerate(deep) if v == i]
        if(index == []):
            break
        
        for x in index:
            for w in ways[x]:
                if(deep[w - 1] == -1):
                    deep[w - 1] = i + 1
                    maps[w - 1] = x + 1
        
    except:
        pass
    
if(-1 in maps):
    print('No')
else:
    print('Yes')
    for i in maps[1:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
root = [set() for i in range(N + 1)]
ans = [0 for i in range(N + 1)]
for i in range(M):
    a, b = map(int, input().split())
    root[a].add(b)
    root[b].add(a)
now = {1}
itta = {1}
while len(now) > 0:
    next = set()
    for i in now:
        next = next | root[i]
    next -= itta
    for i in next:
        num = list(now & root[i])
        num = num[0]
        ans[i] = num
    itta = itta | next
    now = next
print("Yes")
for i in range(2, N + 1):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import queue

n,m = list(map(int, input().split()))
puted = [0]*(n+1)

ab = [[] for i in range(n+1)]
for i in range(m):
	a,b = list(map(int, input().split()))
	ab[a].append(b)
	ab[b].append(a)

q = queue.Queue()
flg = [-1]*n
flg[0] = 0
q.put(1)

while -1 in flg or q.empty():
	item = q.get()
	for i in ab[item]:
		if puted[i]==0:
			flg[i-1]=item
			q.put(i)
			puted[i]=1

if -1 in flg:
	print("No")
	exit()

print("Yes")
for i in range(1,len(flg)):
	print(flg[i])

Submission status: Time Limit Exceeded

Solution code:
import queue

def readInts():
	return list(map(int, input().split()))

def addRoad(a,b):
	global ab
	ab[a].append(b)
	ab[b].append(a)

def addFlag(fr,toarr):
	global flg
	for i in toarr:
		if flg[i]==-1:
			flg[i]=fr
def addQueue(arr):
	global q
	for i in arr:
		q.put(i)
def addFQ(item):
	global flg
	global q
	global ab
	for i in ab[item]:
		if puted[i]==0:
			flg[i-1]=item
			q.put(i)
			puted[i]=1

n,m = readInts()
puted = [0]*(n+1)

ab = [[] for i in range(n+1)]
for i in range(m):
	a,b = readInts()
	addRoad(a,b)

q = queue.Queue()
flg = [-1]*n
flg[0] = 0
q.put(1)

while -1 in flg or q.empty():
	item = q.get()
	#addFlag(item,ab[item])
	#addQueue(ab[item])
	addFQ(item)

if -1 in flg:
	print("No")
	exit()

print("Yes")
for i in range(1,len(flg)):
	print(flg[i])

Submission status: Time Limit Exceeded

Solution code:
import math
import queue
from collections import defaultdict
def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()
def factorization(n):
	res = []
	if n%2==0:
		res.append(2)
	for i in range(3,math.floor(n//2)+1,2):
		if n%i==0:
			c = 0
			for j in res:
				if i%j==0:
					c=1
			if c==0:
				res.append(i)
	return res
def fact2(n):
	p = factorization(n)
	res = []
	for i in p:
		c=0
		z=n
		while 1:
			if z%i==0:
				c+=1
				z/=i
			else:
				break
		res.append([i,c])
	return res
def fact(n):#階乗
	ans = 1
	m=n
	for _i in range(n-1):
		ans*=m
		m-=1
	return ans
def comb(n,r):#コンビネーション
	if n<r:
		return 0
	l = min(r,n-r)
	m=n
	u=1
	for _i in range(l):
		u*=m
		m-=1
	return u//fact(l)
def combmod(n,r,mod):
	return (fact(n)/fact(n-r)*pow(fact(r),mod-2,mod))%mod
def printQueue(q):
	r=copyQueue(q)
	ans=[0]*r.qsize()
	for i in range(r.qsize()-1,-1,-1):
		ans[i] = r.get()
	print(ans)
def dq():
	return queue.deque()
class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1]*n

	def find(self, x): # root
		if self.parents[x]<0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self,x,y):
		x = self.find(x)
		y = self.find(y)

		if x==y:
			return

		if self.parents[x]>self.parents[y]:
			x,y = y,x

		self.parents[x]+=self.parents[y]
		self.parents[y]=x

	def size(self,x):
		return -1*self.parents[self.find(x)]

	def same(self,x,y):
		return self.find(x)==self.find(y)

	def members(self,x): # much time
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i)==root]

	def roots(self):
		return [i for i,x in enumerate(self.parents) if x<0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()} # 1~n
def bitArr(n):#ビット全探索
	x = 1
	zero = "0"*n
	ans = []
	ans.append([0]*n)
	for i in range(2**n-1):
		ans.append(list(map(lambda x:int(x),list((zero+bin(x)[2:])[-1*n:]))))
		x+=1
	return ans;
def arrsSum(a1,a2):
	for i in range(len(a1)):
		a1[i]+=a2[i]
	return a1
def maxValue(a,b,v):
	v2 = v
	for i in range(v2,-1,-1):
		for j in range(v2//a+1): #j:aの個数
			k = i-a*j
			if k%b==0:
				return i
	return -1
def copyQueue(q):
	nq = queue.Queue()
	n = q.qsize()
	for i in range(n):
		x = q.get()
		q.put(x)
		nq.put(x)
	return nq

def addRoad(a,b):
	global ab
	ab[a].append(b)
	ab[b].append(a)

def addFlag(fr,toarr):
	global flg
	for i in toarr:
		if flg[i]==-1:
			flg[i]=fr
def addQueue(arr):
	global q
	for i in arr:
		q.put(i)
def addFQ(item):
	global flg
	global q
	global ab
	for i in ab[item]:
		if puted[i]==0:
			flg[i-1]=item
			q.put(i)
			puted[i]=1

n,m = readInts()
puted = [0]*(n+1)

ab = [[] for i in range(n+1)]
for i in range(m):
	a,b = readInts()
	addRoad(a,b)

q = queue.Queue()
flg = [-1]*n
flg[0] = 0
q.put(1)

while -1 in flg or q.empty():
	item = q.get()
	#addFlag(item,ab[item])
	#addQueue(ab[item])
	addFQ(item)

if -1 in flg:
	print("No")
	exit()

print("Yes")
for i in range(1,len(flg)):
	print(flg[i])

Submission status: Time Limit Exceeded

Solution code:
import math
import queue
from collections import defaultdict
def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()
def factorization(n):
	res = []
	if n%2==0:
		res.append(2)
	for i in range(3,math.floor(n//2)+1,2):
		if n%i==0:
			c = 0
			for j in res:
				if i%j==0:
					c=1
			if c==0:
				res.append(i)
	return res
def fact2(n):
	p = factorization(n)
	res = []
	for i in p:
		c=0
		z=n
		while 1:
			if z%i==0:
				c+=1
				z/=i
			else:
				break
		res.append([i,c])
	return res
def fact(n):#階乗
	ans = 1
	m=n
	for _i in range(n-1):
		ans*=m
		m-=1
	return ans
def comb(n,r):#コンビネーション
	if n<r:
		return 0
	l = min(r,n-r)
	m=n
	u=1
	for _i in range(l):
		u*=m
		m-=1
	return u//fact(l)
def combmod(n,r,mod):
	return (fact(n)/fact(n-r)*pow(fact(r),mod-2,mod))%mod
def printQueue(q):
	r=copyQueue(q)
	ans=[0]*r.qsize()
	for i in range(r.qsize()-1,-1,-1):
		ans[i] = r.get()
	print(ans)
def dq():
	return queue.deque()
class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1]*n

	def find(self, x): # root
		if self.parents[x]<0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self,x,y):
		x = self.find(x)
		y = self.find(y)

		if x==y:
			return

		if self.parents[x]>self.parents[y]:
			x,y = y,x

		self.parents[x]+=self.parents[y]
		self.parents[y]=x

	def size(self,x):
		return -1*self.parents[self.find(x)]

	def same(self,x,y):
		return self.find(x)==self.find(y)

	def members(self,x): # much time
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i)==root]

	def roots(self):
		return [i for i,x in enumerate(self.parents) if x<0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()} # 1~n
def bitArr(n):#ビット全探索
	x = 1
	zero = "0"*n
	ans = []
	ans.append([0]*n)
	for i in range(2**n-1):
		ans.append(list(map(lambda x:int(x),list((zero+bin(x)[2:])[-1*n:]))))
		x+=1
	return ans;
def arrsSum(a1,a2):
	for i in range(len(a1)):
		a1[i]+=a2[i]
	return a1
def maxValue(a,b,v):
	v2 = v
	for i in range(v2,-1,-1):
		for j in range(v2//a+1): #j:aの個数
			k = i-a*j
			if k%b==0:
				return i
	return -1
def copyQueue(q):
	nq = queue.Queue()
	n = q.qsize()
	for i in range(n):
		x = q.get()
		q.put(x)
		nq.put(x)
	return nq

def addRoad(a,b):
	global ab
	ab[a].append(b)
	ab[b].append(a)

def addFlag(fr,toarr):
	global flg
	for i in toarr:
		if flg[i]==-1:
			flg[i]=fr
def addQueue(arr):
	global q
	for i in arr:
		q.put(i)
def addFQ(item):
	global flg
	global q
	global ab
	for i in ab[item]:
		if flg[i-1]==-1:
			flg[i-1]=item
		if puted[i]==0:
			q.put(i)
			puted[i]=1

n,m = readInts()
puted = [0]*(n+1)

ab = [[] for i in range(n+1)]
for i in range(m):
	a,b = readInts()
	addRoad(a,b)

q = queue.Queue()
flg = [-1]*n
flg[0] = 0
q.put(1)

while -1 in flg or q.empty():
	item = q.get()
	#addFlag(item,ab[item])
	#addQueue(ab[item])
	addFQ(item)

if -1 in flg:
	print("No")
	exit()

print("Yes")
for i in range(1,len(flg)):
	print(flg[i])

Submission status: Time Limit Exceeded

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
#dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])}
ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda :int(input())
ip = lambda :[int(w) for w in input().split()]

n,m = ip()
graph = {i:[] for i in range(1,n+1)}
for i in range(m):
    a,b = ip()
    graph[a].append(b)
    graph[b].append(a)

parent = {i:-1 for i in range(1,n+1)}
parent[1] = 0
q = [1]
while len(q):
    u = q[0]
    q.pop(0)
    for v in graph[u]:
        if parent[v] == -1:
            q.append(v)
            parent[v] = u

if -1 in list(parent.values()):
    print("No")
    exit()
print("Yes")
for i in range(2,n+1):
    print(parent[i])