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 sys
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

def MII_split():
    return map(int, input().split())

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

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

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

import heapq

def dijkstra(s, n, w, cost):
    # 始点sから各頂点への最短距離
    # n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    signs = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    q = []
    heapq.heappush(q, (0, s))  # 始点をpush

    while len(q) != 0:
        # v = -1
        # # まだ使われてない頂点の中から最小の距離のものを探す
        # for i in range(n):
        #     if (not used[i]) and (v == -1):
        #         v = i
        #     elif (not used[i]) and d[i] < d[v]:
        #         v = i
        # if v == -1:
        #     break
        # used[v] = True
        prov_cost, v = heapq.heappop(q)  # pop

        # プライオリティキューに格納されている最短距離が，現在計算できている最短距離より大きければ，distの更新をする必要はない
        if d[v] < prov_cost:
            continue

        # print(v)

        for j in range(n):
            c = cost[v][j]
            if c != float('inf') and d[j] > d[v] + c:
                d[j] = d[v] + c
                heapq.heappush(q, (d[j], j))  # キューに新たな仮の距離の情報をpush
                signs[j] = v + 1
    return d, signs

N, M = MII_split()
cost = [[float('inf') for _ in range(N)] for _ in range(N)]
for _ in range(M):
    x, y = MII_split()
    # if x > y:
    #     x, y = y, x
    cost[x - 1][y - 1] = 1
    cost[y - 1][x - 1] = 1

d, signs = dijkstra(0, N, M, cost)

# print(d, signs[1:])

if float('inf') in signs[1:]:
    print('No')
else:
    print('Yes')
    print_list_in_2D(signs[1:])

Submission status: Time Limit Exceeded

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

l = [[False for _ in range(n)] for __ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    l[a-1][b-1] = l[b-1][a-1] = True

p = [0 for _ in range(n)]
s = [1]
j = 0
while j < n-1:
    r = s[j]
    j += 1
    for i, b in enumerate(l[r-1]):
        if b and i+1 not in s:
            p[i] = r
            s.append(i+1)

if 0 in p[1:]:
    print('No')
else:
    print('Yes')
    for pp in p[1:]:
        print(pp)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import dijkstra
import numpy as np

N,M = map(int,input().split())
#V=[[] for _ in range(N)]
row=[0]*M
col=[0]*M
data=[1]*(M)
for i in range(M):
    a,b = map(int, input().split())
    row[i]=a-1
    col[i]=b-1

s=0
graph=coo_matrix((data, (row, col)), shape=(N,N))
dist_matrix,predecessors = dijkstra(csgraph=graph, directed=False, indices = s, unweighted=True, return_predecessors=True)
#print(dist_matrix)
#print(predecessors)
print('Yes')
print(*[e+1 for e in predecessors[1:]],sep='\n')

Submission status: Time Limit Exceeded

Solution code:
N, M = list(map(int, input().split()))
a = []
b = []
for i in range(M):
    aa, bb = list(map(int, input().split()))
    a.append(aa-1)
    b.append(bb-1)
    
table = [0] * N
ans = [0] * N

table[0] = 1

miti = [[] for i in range(N)]


for i in range(M):
    miti[a[i]].append(i)
    miti[b[i]].append(i)


#start
q = [0]
cnt = 1

while(q):
    
    if cnt==N:
        break
    
    x = q[0]
    
    for i in range(len(miti[x])):
        m = miti[x][i]
        if a[m] == x and table[b[m]]==0:
            table[b[m]]=1
            ans[b[m]]=a[m]+1
            q.append(b[m])
            cnt += 1
        if b[m] == x and table[a[m]]==0:
            table[a[m]]=1
            ans[a[m]]=b[m]+1
            q.append(a[m])      
            cnt +=1
    
    q.pop(0)

if sum(table)==N:
    print("Yes")
    for i in range(1,N):
        print(ans[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import math
(r, p)=[int(n) for n in input().split()]
route_list=[[0 for j in range(r)] for i in range(r)]
for i in range(p):
  (x, y)=[int(n)-1 for n in input().split()]
  route_list[x][y] = 1
  route_list[y][x] = 1 

node_num = len(route_list)

unsearched_nodes = list(range(node_num))
distance = [math.inf] * node_num
previous_nodes = [-1] * node_num
distance[0] = 0

def initial():
  unsearched_nodes = list(range(node_num))
  distance = [math.inf] * node_num
  previous_nodes = [-1] * node_num
  distance[0] = 0

def get_target_min_index(min_index, distance, unsearched_nodes):
    start = 0
    while True:
        index = distance.index(min_index, start)
        found = index in unsearched_nodes
        if found:
            return index
        else:
            start = index + 1

while(len(unsearched_nodes) != 0):
    posible_min_distance = math.inf
    for node_index in unsearched_nodes:
        if posible_min_distance > distance[node_index]: 
            posible_min_distance = distance[node_index]
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes)
    unsearched_nodes.remove(target_min_index)

    target_edge = route_list[target_min_index]
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis
                previous_nodes[index] =  target_min_index

ans=[]
for i in range(1, r):
  initial()
  previous_node = i
  string=""
  while previous_node != -1:
    if previous_node !=0:
        string += str(previous_node + 1) + " <- "
    else:
        string += str(previous_node + 1)
    previous_node = previous_nodes[previous_node]
  if len(string.split()) > 2:
    ans.append(string.split()[2])
  else:
    ans.append("No")

if "No" in ans:
  print("No")
else:
  print("Yes")
  for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx

path = nx.Graph()
room_num, path_num = map(int, input().split())
for i in range(1, room_num):
	path.add_node(i)
for _ in range(path_num):
    a, b = map(int, input().split())
    path.add_edge(a, b)
if nx.is_connected(path):
    print("Yes")
    ans = []
    for n in range(2, room_num+1):
        preans = nx.shortest_path(path, target=1)
    for n in range(2, room_num+1):
    	print(preans[n][1])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main():
    N, M = map(int, input().split())

    road = [[] for _ in range(N)]
    for i in range(M):
        ai, bi = map(int, input().split())
        for j in range(1, N+1):
            if ai == j:
                road[j-1].append(bi)
            elif bi == j:
                road[j-1].append(ai)

    q = deque()
    seen = [-1 for _ in range(N)]

    q.append(1)
    seen[0] = 0
    f = 1

    while q:
        n = q.popleft()
        if f == N:
            break
        
        else:
            for next in road[n-1]:
                if seen[next-1] == -1:
                    seen[next-1] = n
                    q.append(next)
                    f += 1

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def dijkstra(s,n,w,cost):
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    past=[[] for i in range(n)] 
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
            if(d[j]>d[v]+cost[v][j]):
                d[j]=d[v]+cost[v][j]
                past[j].append(v)
            else:
                d[j]=d[j]
                # past[j].append(j)



    return d,used,past

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

ans,used,past= dijkstra(0,n,m,cost)
if(False in used):print("No")
else:
    print("Yes")
    for i in past[1:]:
        print(i[0]+1)

Submission status: Time Limit Exceeded

Solution code:

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes) if b else print(no)
from collections import Counter,deque,defaultdict
# import itertools
# import math
import networkx as nx
# from bisect import bisect_left,bisect_right
n,m=n1()
ab=n3(m)

ans={}
d=[0]*(n+1)
p=[1]
p2=[]
while len(ans)<n-1:
    for c in p:
        d[c]=1
        for a,b in ab:
            if a==c and d[b]==0:
                p2.append(b)
                d[b]=1
                ans[b]=a
            if b==c and d[a]==0:
                p2.append(a)
                d[a]=1
                ans[a]=b
    p=p2.copy()
    p2=[]

A=list(ans.items())
A.sort(key=lambda x:x[0])
print("Yes")
for line in A:
    print(line[1])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
roots = []
next_room = []
out = [0]*n
out[0] = 'Yes'
for _ in range(m):
    root = list(map(int, input().split()))
    if 1 in root:
        if root[0]==1:
            out[root[1]-1]=1
        else:
            out[root[0]-1]=1
    else:
        roots.append(root)
while True:
    out_tmp = out.copy()
    for root in roots:
        if out[root[0]-1] != 0 and out[root[1]-1] == 0:
            out_tmp[root[1]-1] = root[0]
        elif out[root[1]-1] != 0 and out[root[0]-1] == 0:
            out_tmp[root[0]-1] = root[1]
    out = out_tmp
    if out.count(0)==0:
        break
for o in out:
    print(o)

Submission status: Time Limit Exceeded

Solution code:

def main():
    import sys
    input = sys.stdin.buffer.readline
    #n = int(input())
    #l = list(map(int, input().split()))
    '''
    A=[]
    B=[]
    for i in range():
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)'''

    n,m = map(int, input().split())
    r=[[0 for i in range(n)]for i in range(n)]
    start = [0, 0]
    #print(bfs(h, w, m, start))
    for i in range(m):
        a,b=map(int, input().split())
        r[a-1][b-1]=b-1
        r[b-1][a-1]=a-1
    #print(r)
    
    from collections import deque
    d = [0 for i in range(n)]
    visited=[False for i in range(n)]
    flg = True
    queue=deque([0])
    dd=0
    while queue:
        now=queue.popleft()
        visited[now]=True
        #print(now)
        for i in r[now]:
            if not visited[i]:
                queue.append(i)
                visited[i]=True
                d[i]=now
    #print(d)
    if flg:
        print("Yes")
        for i in range(1,n):
            print(d[i]+1)
    else:
        print("No")


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

# G.add_nodes_from(list(range(1,N+1)))
for _ in range(M):
    A,B = map(int,input().split())
    G.add_edge(A, B)

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

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

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, M = map(int, input().split())
    g = [[] for _ in range(N)]

    A, B = [0]*M, [0]*M
    for i in range(M):
        A[i], B[i] = map(int, input().split())
        g[A[i]-1].append(B[i]-1)
        g[B[i]-1].append(A[i]-1)

    ans_list = [-1] * N

    queue = [0]
    seen = [False]*N

    while queue:
        qi = queue.pop(0)
        # qi から 1 遠い頂点が gi
        for gi in g[qi]:
            if seen[gi] == False:
                queue.append(gi)
                if ans_list[gi] == -1:
                    ans_list[gi] = qi
                    seen[gi] = True
        if len(set(seen)) == 1:
            break

    print("Yes")
    for ans in ans_list[1:]:
        print(ans+1)  # 1-index に直す

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
rootList = [list(map(int, input().split())) for _ in range(m)]

def search(rank):
    result = []
    for i in rootList:
        if rank == i[0]-1:
            result.append(i[1]-1)
        if rank == i[1]-1:
            result.append(i[0]-1)
    return result

ans = [-1 for _ in range(n)]
room = [0]
while -1 in ans:
    nextroom = []
    for i in room:
        far = search(i)
        for j in far:
            if ans[j] == -1:
                ans[j] = i + 1
        nextroom += far
    room = nextroom

for i in range(n):
    if i == 0:
        print("Yes")
    else:
        print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

A,B=[0]*M,[0]*M
route=[[float("inf")]*N for _ in range(N)]
for i in range(M):
    A[i],B[i]=map(int,input().split())
    A[i]-=1
    B[i]-=1
    route[A[i]][B[i]]=1
    route[B[i]][A[i]]=1

visited=1
not_visited=0

size=len(route)
cost=[float("inf") for _ in range(size)]
visited=[not_visited for _ in range(size)]
before=[None for _ in range(size)]
cost[0]=0

while True:
    MIN=float("inf")
    for i in range(size):
        if visited[i]==not_visited and cost[i]<MIN:
            x = i
            MIN = cost[x]
    if MIN == float("inf"):
        break
    visited[x] = visited

    for i in range(size):
        if cost[i]>route[x][i]+cost[x]:
            cost[i]=route[x][i]+cost[x]
            before[i]=x


def count(start,before):
    now=start
    ret=1
    while True:
        if before[now]==0:
            break
        else:
            ret+=1
            now=before[now]
    return ret

for i in range(1,N):
    if count(i,before)==cost[i]:
        continue
    else:
        print("No")
        exit()

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

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop, heapify
def trace(s, t, ancestors):
    route = [t]
    c = t
    while True:
        a = ancestors[c]
        assert a is not None, 'Failed to trace'
        route.append(a)
        if a == s:
            break
        c = ancestors[c]
    route.reverse()
    return route


def dijkstra(s, t, links):
    heap = [(*l, s) for l in links[s]]
    heapify(heap)
    visited = set()
    ancestors = [None] * N
    while heap:
        cost, node, ancestor = heappop(heap)
        if node in visited:
            continue
        visited.add(node)
        ancestors[node] = ancestor
        if node == t:
            return cost, trace(s, t, ancestors)
        for cost2, node2 in links[node]:
            if node2 not in visited:
                heappush(heap, (cost + cost2, node2, node))
    return float('inf'), None

N, M = map(int, input().split())
links = [set() for _ in range(N)]
for _ in range(M):
    x, y = map(int, input().split())
    links[x-1].add((1, y-1))
    links[y-1].add((1, x-1))
ans = [0]*N
done = set()
for i in range(1, N):
    if i in done:
        continue
    tmp = dijkstra(0, i, links)
    for j in range(1, len(tmp[1])):
        ans[tmp[1][j]] = tmp[1][j-1] + 1
        done.add(tmp[1][j])
print("Yes")
for i in range(1,N):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m = map(int,input().split())
route = [[False for x in range(n+1)] for x in range(n+1)]
q = deque()
q.append([1,0,-1])
ans = [[float("inf"),0] for x in range(n+1)]
for i in range(m):
    a,b = map(int,input().split())
    route[a][b] = True
    route[b][a] = True
while(len(q) > 0):
    pos,point,before = q.popleft()
    if(ans[pos][0] > point):
        ans[pos][0] = point
        ans[pos][1] = before
    for x in range(n+1):
        if(route[pos][x]):
            q.append([x,point+1,pos])
            route[pos][x] = False
            route[x][pos] = False
for i in ans[1:]:
    if(i[0] == float("inf")):
        print("No")
        break
else:
    print("Yes")
    for i in ans[2:]:
        print(i[1])

Submission status: Time Limit Exceeded

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


def solve():
    N, M = map(int, input().split())
    loadmap = [[] for _ in range(N + 1)]
    for _ in range(M):
        A, B = map(int, input().split())
        loadmap[A].append(B)
        loadmap[B].append(A)

    dbmap = [[float('inf'), -1] for _ in range(N + 1)]  # 部屋の深度, しるべ

    # rooms = [[0, 1, 0]]  # [移動前の部屋, 移動後(現在)の部屋, 深度]
    rooms = deque()
    rooms.append([0, 1, 0])
    while rooms:
        # br, r, d = heappop(rooms)
        br, r, d = rooms.popleft()
        if d <= dbmap[r][0]:
            # update room data
            dbmap[r][0] = d
            dbmap[r][1] = br
            # add new room data
            for l in loadmap[r]:
                # heappush(rooms, [r, l, d + 1])
                rooms.append([r, l, d + 1])

    if min([db[1] for db in dbmap[1:]]) <= -1:
        print('No')
    else:
        print('Yes')
        for db in dbmap[2:]:
            print(db[1])


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

a = []
b = []

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

#各部屋から行ける部屋
c = [[] for i in range(n)]

for i in range(m):
	c[a[i]].append(b[i])
	c[b[i]].append(a[i])

s = [0]
f = []

#部屋1からの距離
d = [10**6]*n
d[0] = 0

while s!=[]:
	x = s[-1]
	s.pop(-1)
	if not(x in f):
		for i in c[x]:
			if not((i in s) or (i in f)):
				s.append(i)
			d[i] = min(d[i], d[x]+1)
		f.append(x)

print('Yes')
for i in range(1,n):
	m = 10**6
	ans = 0
	for j in c[i]:
		if d[j]<m:
			m = d[j]
			ans = j+1
	print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N, M = map(int, input().split())
adj = [[float("inf") for i in range(N)] for j in range(N)]
signs = [-1 for i in range(N)]
non_patrolled = set(range(1, N))
signs[0] = 1

for _ in range(M):
  x,y = map(int,input().split())
  adj[x - 1][y - 1] = 1
  adj[y - 1][x - 1] = 1

queue = deque([0])
dist = 0

while len(queue) > 0:
  cur = queue.popleft()
  used = set()
  for i in non_patrolled:
    c = adj[cur][i]
    if c == 1:
      if signs[i] == -1:
        queue.append(i)
        signs[i] = cur
        used.add(i)
  non_patrolled = non_patrolled - used

if all([sign != -1 for sign in signs]):
  print("Yes")
  for sign in signs[1:]:
    print(sign + 1)
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
import math
import queue

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=qb
	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


n,w = readInts()
ano = [-1]*n

def dijkstra(s,n,w,cost):
	d = [float("inf")]*n
	used = [False]*n
	d[s] = 0
	global ano

	while True:
		v = -1
		for i in range(n):
			if (not used[i]) and (v==-1):
				v = i
			elif (not used[i]) and d[i]<d[v]:
				v = i
		if v==-1:
			break
		used[v] = True

		for j in range(n):
			if d[v]+cost[v][j]<d[j]:
				d[j] = d[v]+cost[v][j]
				#ano[j] = str(ano[j])+str(v)
				if ano[j]==-1:
					ano[j]=v
				else:
					print("No")
					exit()
	return ano


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

for i in range(w):
	x,y = readInts()
	cost[x-1][y-1] = 1
	cost[y-1][x-1] = 1
ans = dijkstra(0,n,w,cost)
print("Yes")
for i in range(1,len(ans)):
	print(ans[i]+1)

#print(ano)

Submission status: Time Limit Exceeded

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

paths = set()
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    paths.add((a, b))

rooms = [-1] * N
rooms[0] = 0
marks = [-1] * (N-1)
step = 1
for step in range(1, N):
    key_rooms = []
    for i, room in enumerate(rooms):
        if room == step-1:
            key_rooms.append(i)
    kick_list = []
    for key_room in key_rooms:
        for path in paths:
            if key_room in path:
                else_room = path[0]
                if else_room == key_room:
                    else_room = path[1]
                kick_list.append(path)
                if rooms[else_room] == -1:
                    rooms[else_room] = step
                    marks[else_room-1] = key_room
    for kick in kick_list:
        if kick in paths:
            paths.remove(kick)

flag = True
for room in rooms[1:]:
    if room == 0:
        flag = False
        print('No')
        break

if flag:
    print('Yes')
    for i in marks:
        print(i+1)

Submission status: Time Limit Exceeded

Solution code:
def search(li, n, target):
    ret = []
    for k in range(1, n+1):
        if [k, target] in li or [target, k] in li:
            ret.append(k)
    return ret


N, M = map(int, input().split())
path = [[0]*2 for _ in range(M)]
for i in range(M):
    path[i][0], path[i][1] = map(int, input().split())
last = [1, ]
flag = [1, ]
path0 = path.copy()
result = [0 for m in range(N)]

for k in range(N-1):
    now = []
    for j in last:
        for i in range(1, N+1):
            if i in flag:
                continue
            if [i, j] in path:
                path.remove([i, j])
                result[i-1] = j
                flag.append(i)
                now.append(i)
            if [j, i] in path:
                path.remove([j, i])
                result[i-1] = j
                flag.append(i)
                now.append(i)
    last = now.copy()

if result == [0 for m in range(N)]:
    print("No")
else:
    print("Yes")
    for i in range(1, len(result)):
        print(result[i])

Submission status: Time Limit Exceeded

Solution code:
def main():
    n,m = map(int,input().split())
    ab = []
    cnt = [0] * n
    road = [[] for i in range(n)]

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

    dist = [10**7] * n
    dist[0] = 0
    ans = [0] * n
    cnt = 0
    while True:
        for i, aa in enumerate(road):
            for j, t in enumerate(aa):
                if dist[i] > dist[t]:
                    dist[i] = dist[t]+1
                    ans[i] = t + 1
                    flg = True


        cnt += 1
        if cnt == 10000:
            break
        if flg :
            flg = False
            continue
        else:
            break

    f = 'Yes'
    for i in range(n):
        if dist[i] == 10**7:
            f = 'No'
            break
        else:
            continue
    print(f)
    for i in range(1,n):
        print(ans[i])


if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math
from queue import Queue
from collections import defaultdict

n, m = [int(i) for i in input().split()]


root = defaultdict(lambda: defaultdict(int))


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

check = [0 for _ in range(n + 1)]
check[1] = 1

q = Queue()
q.put(1)

while (not q.empty()):
    now = q.get()
    for i in range(1, n + 1):
        if (root[now][i] == 1 and check[i] == 0):
            check[i] = now
            q.put(i)

flag = 1
for i in range(2, n + 1):
    if (check[i] == 0):
        flag = 0

if (flag == 1):
    print("Yes")
    for j in range(2, n + 1):
        print(check[j])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M = map(int, input().split())
A_B_list = [[int(i) for i in input().split()] for j in range(M)]
ans = np.zeros(N)
next_list = [1]
next_next_list = []
flag = False
while np.any(ans==0):
    for nxt in next_list:
        for ab in A_B_list: #1に繋がってるやつを消す
            if nxt == ab[0] and ans[ab[1]-1] == 0:
                ans[ab[1]-1] = nxt
                next_list.append(ab[1])
                
            elif nxt == ab[1] and ans[ab[0]-1] == 0:
                ans[ab[0]-1] = nxt
                next_list.append(ab[0])
                
    if len(next_list)==0:
        flag = True
        break
    next_list = next_next_list

if flag:
    print("No")
else:
    print("Yes")
    for i in ans[1:]:
        print(int(i))