Problem:


Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 2 \times 10^5

1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.



Sample input:
4 4
1 2
2 3
3 4
4 2


Sample output:
Yes
1
2
2

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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(lc[x]) == 0:
        q.queue = False
        return
    
    ind_lis = np.where(lc[x] == 1)
#     print(ind_lis)
    for e in ind_lis[0]:
#         print(e+1)

        lc[x][e] =0
        lc[e][x] =0
        if li[e] == -1:
            li[e] = x
            q.put(e)
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:
def main():
    n,m=map(int,input().split())
    ab = {}
    ab1 = {}
    for _ in range(m):
        a,b=map(int,input().split())
        ab.setdefault(a,[]).append(b)
        ab.setdefault(b,[]).append(a)
        ab1.setdefault(a,[]).append(b)
        ab1.setdefault(b,[]).append(a)
    g = []
    g.append(set([1]))
    marked = set()
    marked.add(1)
    while ab:
        g_add = set()
        for k in g[-1]:
            for x in ab[k]:
                if x not in marked:
                    g_add.add(x)
                    marked.add(x)
            del ab[k]
        g.append(g_add)
    if len(marked) < n:
        print('No')
        return
    print('Yes')
    result = [None] * n
    for i,s in enumerate(g):
        for k in s:
            result[k-1] = [e for e in g[i-1] if e in ab1[k]]
    for i in range(1,n):
        print(result[i][0])

main()

Submission status: Time Limit Exceeded

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

inv = [i for i in range(N-1)]
visited = [1]

path = {i :[] for i in range(1, N+1)}

for i in range(M):
  A, B = map(int, input().split())
  path[A].append(B)
  path[B].append(A)
nows = [1]
for t in range(N):
  buf = []
  for now in nows:
    for p in path[now]:
      if p not in visited:
        buf.append(p)
        visited.append(p)
        inv[p-2]=now
  if len(buf)==0:
    break
  nows = buf
print("Yes")
for i in inv:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

N, M = map(int, input().split())
AB = [[0, 0] for _ in range(M)]
for i in range(M):
  AB[i] = list(map(int, input().split()))
  AB[i][0] -= 1
  AB[i][1] -= 1
AB = np.array(AB)

ikikata = [0 for _ in range(N)]
miti = [0 for _ in range(N)]

idx = deque([0])
j = 0
while idx:
  k = idx.popleft()
  index1 = list(np.where(AB[:, 0] == k)[0])
  index2 = list(np.where(AB[:, 1] == k)[0])
  for i in index1:
    if miti[AB[i][1]] == 0:
      ikikata[AB[i][1]] = 1
      miti[AB[i][1]] = k + 1
      if AB[i][1] in idx:
        continue
      idx.append(AB[i][1])
  for i in index2:
    if miti[AB[i][0]] == 0:
      ikikata[AB[i][0]] = 1
      miti[AB[i][0]] = k + 1
      if AB[i][0] in idx:
        continue
      idx.append(AB[i][0])
  j += 1

if 0 in miti[1:]:
  print('No')
else:
  print('Yes')
  for i in miti[1:]:
    print(int(i))

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

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# input
N, M = map(int, input().split())
Load = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    Load[a].append(b)
    Load[b].append(a)

# process
result = True
sign = [-1]*N
l = [0]
while True:
    for i in l:
        l_ = []
        for j in Load[i]:
            if j == i or sign[j] != -1:
                continue

            sign[j] = i
            l_.append(j)
    
    if not -1 in sign:
        break

    l = l_

sign.pop(0)

# output
print("Yes" if result else "No")
[print(x+1) for x in sign]

Submission status: Time Limit Exceeded

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

roots = [input().split(' ') for _ in range(m)]
for i in range(m):
    roots[i] = [int(x)-1 for x in roots[i]]

dic = {}
all_list = [0]
is_no = False
d_list = [0]
for i in range(n):
    if len(dic) >= n-1:
        break
    if len(d_list) == 0:
        is_no = True
        break
    d_list = []
    a = 0
    while a < m:
        is_next = True
        for b in range(2):
            if roots[a][b] in all_list:
                if not roots[a][abs(b-1)] in d_list and not roots[a][abs(b-1)] in all_list:
                    d_list.append(roots[a][abs(b-1)])
                    dic[roots[a][abs(b-1)]] = roots[a][b] + 1
                roots.pop(a)
                m -= 1
                is_next = False
                break
        if is_next:
            a += 1
    all_list += d_list

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

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=[]
col=[]
data=[1]*(2*M)
for _ in range(M):
    a,b = map(int, input().split())
    row.append(a-1)
    col.append(b-1)
    row.append(b-1)
    col.append(a-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:
import math
from collections import deque

n, m = map(int, input().split())

graph = []

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

dist = [-1] * (n+1)
dist[0] = 0
dist[1] = 0

d = deque()
d.append(1)

guidepost = [-1] * (n+1)

while d:
  v = d.popleft()
  for i, j in graph:
    if dist[i] != -1 and dist[j] != -1:
      continue
    elif i == v:
      dist[j] = dist[v] + 1
      d.append(j)
      if guidepost[j] == -1:
        guidepost[j] = v
      else:
        print("No")
        exit()
    elif j == v:
      dist[i] = dist[v] + 1
      d.append(i)
      if guidepost[i] == -1:
        guidepost[i] = v
      else:
        print("No")
        exit()
  
for i in range(2, len(guidepost)):
  if guidepost[i] == -1:
    print("No")
    exit()

print("Yes")
for i in range(2, len(guidepost)):
  print(guidepost[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline

N, M = map(int, readline().split())
ans = []
graph = [[] for _ in range(N+1)]

for _ in range(M):
    a, b = map(int, readline().split())
    graph[a].append(b)
    graph[b].append(a)

root = 1
q = [root]
checked = [0] * (N + 1)
checked[root] = 1
order = []

while q:
    x = q.pop(0)
    for y in graph[x]:
        if checked[y]:
            continue
        ans.append(x)
        order.append(y-2)
        checked[y] = 1
        q.append(y)

if len(order) != N - 1:
    print('No')
else:
    print('Yes')
    for i in range(len(order)):
        j = order.index(i)
        print(ans[j])

Submission status: Time Limit Exceeded

Solution code:
N, M  = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]
tunagari = [0]*N
ans = [0]*N
kai = [[1]]
tunagari[0] =1
for i in range(N):
    for j in kai[i]:
        sou = []
        for k in X:
            if k[0] == j and tunagari[k[1]-1] == 0:
                sou.append(k[1])
                tunagari[k[1]-1] = j
            elif k[1] == j  and tunagari[k[0]-1] == 0:
                sou.append(k[0])
                tunagari[k[0]-1] = j
        kai.append(sou)
print("Yes")
for i in range(1,N):
    print(tunagari[i])

Submission status: Time Limit Exceeded

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

road = {k:[] for k in range(1,n+1)}
for _ in range(m):
  a,b = map(int,input().split())
  road[a].append(b)
  road[b].append(a)


next_visited = [1]
visited = [1]
temp_next = []

visit_num = {}

while True:
  temp_next = []
  for room in next_visited:
    ava_room = road[room]
    for r in ava_room:
      if r not in visited:
        visit_num[r] = room
        temp_next.append(r)
        visited.append(r)
        
  if temp_next == []:
    break
  next_visited = temp_next

if len(visit_num) != n-1:
  print('No')

else:
  print('Yes')
  for v in sorted(visit_num.items()):
    print(v[1])

Submission status: Time Limit Exceeded

Solution code:
import math
import queue
from collections import defaultdict
import itertools as it

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

X=[list(map(int,input().split())) for i in range(M)]
Y=[0 for i in range(N)]
Y[0]=-1
Z=[[] for j in range(N)]

import copy


for i in X:
  Z[i[0]-1].append(i[1]-1)
  Z[i[1]-1].append(i[0]-1)

  
item =[0]
while (0 in Y):
  note=[]
  for i in item:
    
    
    for j in Z[i]:
      Z[j].remove(i)
      
      if Y[j]==0:
        Y[j]=i+1
        note=note+[j]
    Z[i]=[]
  item=copy.deepcopy(note)
print("Yes")
for i in Y:
  if i==-1:
    continue
  print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    n, m = map(int, input().split())
    g = [[] for _ in range(n)]
    for _ in range(m):
        a, b = map(lambda x: int(x) - 1, input().split())
        g[a].append(b)
        g[b].append(a)
    max_val = 10 ** 9 + 7
    dist = [max_val for _ in range(n)]
    prev = [-1 for _ in range(n)]
    dist[0] = 0
    q = deque([0])
    cnt = 1
    while q:
        now = q.popleft()
        for next in g[now]:
            if dist[now] + 1 < dist[next]:
                if prev[next] < 0:
                    cnt += 1
                q.appendleft(next)
                prev[next] = now + 1
                dist[next] = dist[now] + 1
    if cnt == n:
        print("Yes")
        for i in range(1, n):
            print(prev[i])
    else:
        print("No")


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

list1=[[] for i in range(N)]
a=[1,1]

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

kyori=[M+1]*N
sirube=[None]*N

kyori[0]=0

k_list=list1[0]
k_list=[]
for i in list1[0]:
    k_list.append([1,i])

nk_list=[]
for k in range(M):
    for n in k_list:
        if kyori[n[1]-1]>k:
            kyori[n[1]-1]=k+1
            nk_list.append(n[1])
            sirube[n[1]-1]=n[0]
        
    
    k_list=[]
    for i in nk_list:
        for j in list1[i-1]:
            k_list.append([i,j])


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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=map(int,input().split())
ab=[list(map(int,input().split())) for i in range(M)]
l=[0]*N
que=deque([])
que.append(1)
while que:
  if 0 not in l:
    exit()
  p=que.popleft
  for i in range(M):
    if ab[i][0]==p:
      que.append(ab[i][1])
      l[ab[i][1]-1]=p
    if ab[i][1]==p:
      que.append(ab[i][0])
      l[ab[i][0]-1]=p
print("Yes")
print(*l)

Submission status: Time Limit Exceeded

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

import heapq

def dijkstra(edges,num_v,start,goal):
      dist = [float("inf")] * num_v
      dist[start] = 0
      q = []
      heapq.heappush(q,[0,[start]])#[0,0]とは1番目に頂点のインデックス、0番目に頂点までのコストを格納する
    
      while len(q) >0:
        #ヒープから取り出し
        _,u = heapq.heappop(q)
        last = u[-1]
        if last == goal:
          return u
        for i in edges[last]:
            if dist[i] > dist[last] + 1:
                #頂点までのコストが更新できれば更新してヒープに登録
                dist[i] = dist[last] + 1
                heapq.heappush(q,[dist[last] + 1,u + [i]])
      return []

result = []
check = True
for i in range(1,n):
  r = dijkstra(m_load,n,i,0)
  if len(r) >= 2:
    
    result.append(r[1] + 1)
  else:
    check = False
if check == False:
  print("No")
else:
  print("Yes")
  for _ in result:
    print(_)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs(AB,N,M):
    #initialize route guide
    g=[0 for n in range(N)]
    g[0]=1
    
    q=deque([1])
    while q:
        x=q.popleft()
        for m in range(M):
            if AB[m][0]==x and g[AB[m][1]-1]==0:
                q.append(AB[m][1])
                g[AB[m][1]-1]=x
            elif AB[m][1]==x and g[AB[m][0]-1]==0:
                q.append(AB[m][0])
                g[AB[m][0]-1]=x
    ok=True if 0 not in g else False
    return ok,g
    
def main():
    #normal input
    N,M=map(int,input().strip().split())
    AB=[list(map(int,input().strip().split())) for _ in range(M)]
    
    ok,g=bfs(AB,N,M)
    
    print("Yes" if ok else "No")
    if ok:
        for n in range(1,N):
            print(g[n])
    
    
    return

if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def dijkstra(s,n,w,cost):
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    global ans 
    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):
               d[j] = min(d[j],d[v]+cost[v][j])
               if min(d[j],d[v]+cost[v][j]) == d[v]+cost[v][j]:
                ans[j] = v+1
    return d
 
n,w = map(int,input().split())
 
cost = [[float("inf") for i in range(n)] for i in range(n)] 
ans = [0]*n
for i in range(w):
    x,y = map(int,input().split())
    cost[x-1][y-1] = 1
    cost[y-1][x-1] = 1
dijkstra(0,n,w,cost)
print("Yes")
for i in range(1, n):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
def run():
    N, M = map(int, sysread().split())
    to = [[] for _ in range(N+1)]
    AB = list(map(int, read().split()))
    for i in range(M):
        a = AB[2*i]
        b = AB[2*i+1]
        to[a].append(b)
        to[b].append(a)

    seen = [False] * (N+1)
    stack = []
    seen[1] = True
    heappush(stack, (0, 1, 0))# (distance, node, prev)
    INF = 1<<64
    mark = [INF] * (N+1)
    done = [False] * (N+1)

    while stack:
        dist, current, prev = heappop(stack)
        seen[current] = True
        if not done[current]:
            done[current] = True
            mark[current] = prev
        for next in to[current]:
            if not seen[next]:
                heappush(stack, (dist+1, next, current))

    print('Yes')
    mark = [str(val) for val in mark]
    print('\n'.join(mark[2:]))

if __name__ == "__main__":
    run()

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(int) for _ in range(n+1)]


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:
def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    ans = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    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):
            d[j] = min(d[j],d[v]+cost[v][j])
            if d[j] >= d[v]+cost[v][j]:
                ans[j] = v+1
    return ans 


n,w = map(int,input().split()) #n:頂点数　w:辺の数

cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(w):
    x,y = map(int,input().split())
    cost[x-1][y-1] = 1
    cost[y-1][x-1] = 1
ans = dijkstra(0,n,w,cost)

print('Yes')
for ans in ans[1:]:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
line = []
sign = []
nextSign_ = [1]


for i in range(n):
    sign.append(None)

for i in range(m):
    in1, in2 = map(int, input().split())
    tmp = (in1, in2)
    line.append(tmp)

for mm in range(m):
    index = 0
    delIndex = []
    nextSign = []
    for i in line:
        for j in nextSign_:
            if i[0] == j:
                if sign[i[1]-1] == None:
                    sign[i[1]-1] = j
                    nextSign.append(i[1])
                    delIndex.append(index)
                    break
            elif i[1] == j:
                if sign[i[0]-1] == None:
                    sign[i[0]-1] = j
                    nextSign.append(i[0])
                    delIndex.append(index)
                    break
        index += 1
    s = 0
    for i in delIndex:
        del line[i-s]
        s += 1
    nextSign_ = nextSign

f = True
for i in range(1, len(sign)):
    if sign[i] == None:
        f = False
if f:
    print("Yes")
    for i in range(1, len(sign)):
        print(sign[i])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import queue
n,m = map(int,input().split())
graph = [[] for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    graph[a-1].append(b)
    graph[b-1].append(a)
ans = [0]* n
flag = [0]*n
q = queue.deque()
q.append(1)
while q:
    tmp = q.popleft()
    flag[tmp-1] = 1
    for i in graph[tmp-1]:
        if flag[i-1] == 0:
            q.append(i)
            if ans[i-1] == 0:
                ans[i-1] = tmp
if sum(flag) == n:
    print('Yes')
    for i in range(1,n):
        print(ans[i])
        
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
def search(li, n, target):
    ret = []
    for k in range(1, n+1):
        if [k, target] in path or [target, k] in path:
            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())
distance = [0 for m in range(N)]
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:
                distance[i-1] = distance[j-1] + 1
                path.remove([i, j])
                result[i-1] = j
                flag.append(i)
                now.append(i)
            if [j, i] in path:
                distance[i - 1] = distance[j - 1] + 1
                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:
import collections

INF = float('inf')

N, M = list(map(int, input().split()))
d = {i: [] for i in range(N)}

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

queue = collections.deque()
queue.append((0, 0))
results = {i: (INF, -1) for i in range(N)}
results[0] = (0, 0)

while queue:
    cost, cur = queue.pop()
    next_list = d[cur]

    for next_cur in next_list:
        next_cost = cost+1
        if next_cost < results[next_cur][0]:
            results[next_cur] = (next_cost, cur)
            queue.append((next_cost, next_cur))

is_no = False
for k, result in results.items():
    if k == 0:
        continue
    if result[1] == -1:
        is_no = True

if is_no:
    print('No')
else:
    print('Yes')
    for k, result in results.items():
        if k == 0:
            continue
        print(result[1] + 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def main():
    n,m=map(int,input().split())
    root=[[0 for i in range(n)] for i in range(n)]
    for i in range(m):
        a,b=map(int,input().split())
        root[a-1][b-1]=1
        root[b-1][a-1]=1
    dict={}
    for i in range(n):
        dict[i]=-1

    start=0
    check=[False]*n
    toVis=deque()
    check[start]=True
    for i in range(len(root[0])):
        if root[0][i]==1:
            toVis.append(i)
            dict[i]=start
        #   print(i,":",start)
            check[i]=True
    while len(toVis)>0:
        now=toVis.popleft()
        #print(now)
        check[now]=True
        for i in range(n):
            if root[now][i]==1 and check[i]==False:
                toVis.append(i)
                dict[i]=now
            # print(i,":",now)
                check[i]=True
    #print(dict)  
    for i in range(1,n):
        if dict[i]==-1:
            print("No")
            return 0
    print("Yes")
    for i in range(1,n):
        print(dict[i]+1)         


if __name__=="__main__":
    main()

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=[]
col=[]
data=[1]*(M)
for _ in range(M):
    a,b = map(int, input().split())
    row.append(a-1)
    col.append(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:

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)

    def bfs(n,r,start):
        #始点に対して終点"g"に着けるか判定
        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")
        return
    bfs(n,r,start)

if __name__ == "__main__":
     main()

Submission status: Time Limit Exceeded

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

n, m = map(int, input().split())
d = [[float("inf")]*n for i in range(n)]

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

a = np.array(d)

q, p = shortest_path(a, return_predecessors=True)


def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])


def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
        if len(path) > 2:
            break
    if i < 0:
        return []
    path.append(i)
    return path[::-1]


if all([i > 0 for i in q[0][1:]]):
    print('Yes')
    for i in range(1, n):
        print(get_path(i, 0, p)[1] + 1)
else:
    print('No')