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

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

lis=[set() for i in range(n)]

for i in range(m):
    aa,bb=list(map(int,input().split()))
    lis[aa-1].add(bb-1)
    lis[bb-1].add(aa-1)


mic=[None for i in range(n)]
pas=[None for i in range(n)]
pas[0]=0
def search(mae,x,length):
    length+=1
    for i in lis[x]:
        if i in mae:
            continue


        if pas[i]==None:
            mic[i]=x
            pas[i]=length
        else:
            if length<pas[i]:
                mic[i]=x
                pas[i]=length

        search(mae+[i],i,length)



search([],0,0)
mic.pop(0)

if None in mic:
    print('No')
else:
    print('Yes')
    for i in range(n-1):
        print(mic[i]+1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop

INT_MAX = 10 ** 9


def main():
  n, m = map(int, input().split())
  ab = (map(int, input().split()) for i in range(m))
  
  g = [[0] * (n+1) for i in range(n+1)]
  gp = [INT_MAX] * (n+1)
  gf = [0] * (n+1)
  
  for a, b in ab:
    g[a][b] = 1
    g[b][a] = 1
  
  h = [(0, 1, 1)]
  
  while h:
    if all(0 < i < INT_MAX for i in gf[2:]):
      break
    p, b, a = heappop(h)
    if p < gp[b]:
      gp[b] = p
      gf[b] = a
    else:
      continue
    for x in range(1, n+1):
      if g[b][x]:
        heappush(h, (p + 1, x, b))
  
  r = gf[2:]
  s = 'Yes' if all(0 < i < INT_MAX for i in r) else 'No'
  print(s)
  if s == 'Yes':
    for i in r:
      print(i)
  
  
  
if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def breath_first_search(start :int, am :list):
    backs = [-1 for _ in range(n)]
    q = deque([start])
    visited = set([start])

    while True:
        if not q: break
        now = q.popleft()
        for node, is_adj in enumerate(am[now]):
            if not is_adj: continue
            if node in visited: continue
            backs[node] = now
            q.append(node)
            visited.add(node)

    return backs

n, m = map(int, input().split())
paths = [list(map(int, input().split())) for _ in range(m)]
am = [[0]*n for _ in range(n)]
for a, b in paths:
    am[a-1][b-1] = 1
    am[b-1][a-1] = 1

backs = breath_first_search(0, am)

if -1 in backs:
    print("Yes")

for back in backs[1:]:
    print(back+1)

Submission status: Time Limit Exceeded

Solution code:

import numpy as np

def search_and_mark(recent_rooms, rooms, AB, count, count_max):
  if None not in rooms:
    return rooms

  tmp_rooms = []
  for r in recent_rooms:
    tmp = AB[np.any(AB == r, axis=1)]
    target = tmp[tmp != r]
    tmp_rooms.extend(target)
    
    for t in target:
      if rooms[t] == None:
        rooms[t] = r

  recent_rooms = list(set(tmp_rooms))
  return search_and_mark(recent_rooms, rooms, AB, count+1, count_max)

def resolve():
  N, M = map(int, input().split(" "))
  rooms = [None] * N

  AB = []
  for m in range(M):
    AB.append([int(x) - 1 for x in input().split(" ")])

  AB = np.array(AB)
  result = search_and_mark([0], rooms, AB, 1, N)

  print("Yes")
  for r in result[1:]:
    print(r + 1)

if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
numlist = []
record = [0] * (n-1)
route = []
flag = 0
for i in range(m):
    temp = list(map(int, input().split()))
    if(temp[0] == 1):
        m -= 1
        record[temp[1] - 2] = 1
        flag += 1
        route.append(temp[1])
    elif(temp[1] == 1):
        m -= 1
        record[temp[0] - 2] = 1
        flag += 1
        route.append(temp[0])
    else:
        numlist += temp
newlist = []
while(flag < n-1):
    newroute = []
    for i in range(len(route)):
        for j in range(m):
            if(numlist[j * 2] == route[i]):
                m -= 1
                if(record[numlist[j * 2 + 1] - 2] == 0):
                    record[numlist[j * 2 + 1] - 2] = route[i]
                    flag += 1
                newroute.append(numlist[j * 2 + 1])
            elif(numlist[j * 2 + 1] == route[i]):
                m -= 1
                if(record[numlist[j * 2] - 2] == 0):
                    record[numlist[j * 2] - 2] = route[i]
                    flag += 1
                newroute.append(numlist[j * 2])
            else:
                newlist += numlist[j*2:j*2 + 2]
        numlist = newlist
        newlist = []
    route = newroute
print("Yes")
for i in record:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M= [int(i) for i in input().split(' ')]
graph = {}
 
for i in range(1,N+1):
  graph[i] = []
 
for j in range(M):
  a, b= [int(i) for i in input().split(' ')]
  graph[a].append(b)
  graph[b].append(a)
    
 
def bfs(graph, start):
  queue = [start]
  miti = {}
  for i in range(1,N+1):
    miti[i] = 0
  while queue:
    label = queue.pop(0)
    for i in graph[label]:
      if miti[i] != 0:
        continue
      queue.append(i)
      miti[i] = label
  return miti
 
miti = bfs(graph, 1)
if miti:
  print('Yes')
  for i in range(2,N+1):
    print(miti[i])
else:
  print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m=map(int,input().split())
ab=[[] for _ in range(n+1)]
for _ in range(m):
  a,b=map(int,input().split())
  ab[a].append(b)
  ab[b].append(a)
l,ll=deque([1]),deque([])
ans=[-1]*n
while l:
  x=l.popleft()
  ll.append(x)
  for i in ab[x]:
    if i in ll:
      continue
    if i in l:
      continue
    l.append(i)
    ans[i-1]=x
print('Yes')
for i in ans[1:]:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
def main():
  N, M = list(map(int, input().split(' ')))

  root = [[] for i in range(N+1)]
  for i in range(M):
    A, B = list(map(int, input().split(' ')))
    root[A].append(B)
    root[B].append(A)

  mitisurube = [-1 for i in range(N+1)]
  next_ = [1]

  while next_:
    now_pos = next_.pop(0)
    for next_pos in root[now_pos]:
      if mitisurube[next_pos] == -1:
        mitisurube[next_pos] = now_pos
        next_.append(next_pos)
  #print('root')
  #print(*root)
  #print('cost')
  #print(*cost)
  #print('mitisirube')
  print('Yes')
  print(*mitisurube[2:], sep='\n')

if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import queue

def dijkstra(g,node_count):
    conf = [0] * node_count
    root = [-1] * node_count

    q = queue.Queue()
    q.put(0)
    root[0] = 0
    conf[0] = 1
    while not q.empty():

        p = q.get()
        conf[p] = 1
        for i in range(node_count):
            if conf[i] == 0 and g[p][i] > 0 and i != p:
                q.put(i)
                root[i] = p
                conf[i] = 1
                if sum(conf) == node_count:
                    break
                
    return root


n, m = map(int, input().split())
r = []
#g = np.zeros((n,n))
g = [[0] * n for i in range(n)]

for i in range(m):
    a, b = map(int, input().split())
    g[a-1][b-1] = 1
    g[b-1][a-1] = 1
    #r.append([a,b])
#for i in range(n):
#    print(g[i])
#c = dijkstra_heapq(g,n,0)
#print(c)
c = dijkstra(g,n)

#c = np.array(c) + 1
#print(c)
ans = []
for i in range(1,n):
    if c[i] >= 0:
        ans.append(c[i]+1)
    else:
        print('No')
        exit()

print('Yes')
for i in range(len(ans)):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import math
N, M = map(int, input().split())

#K = int(input())
#S = input()

path = np.array([[float("inf") for i in range(N)] for i in range(N)] )

for m in range(M):
    A_m, B_m = map(int, input().split())
    path[A_m-1][B_m-1] = 1
    path[B_m-1][A_m-1] = 1
    
sign = np.array([0 for i in range(N)])
nodes = [[] for i in range(N)]
#all_nodes = [i for i in range(N)]

nodes[0] = [0]
#all_nodes.pop(0)
#print(path)

for n in range(N-1):
    #1(0)から距離n+1のものを探す
    if nodes[n] == []: break
    if np.shape(nodes[n])[-1] == 1:
        roots = nodes[n]
    else:
        roots = nodes[n][0]
    #print('roots', roots)
    for s_n in roots:
        connected_idx = np.where(path[s_n]==1)[-1]
        root_idx = s_n#np.where(path[nodes[n]]==1)[0]
        #print('con', connected_idx)
        #print('root', root_idx)
        #print(sign[connected_idx])
        new_idx = np.where(sign[connected_idx]==0)[-1]
        connected_idx = connected_idx[new_idx]
        sign[connected_idx] = root_idx + 1
        nodes[n+1].append(connected_idx)
    #print(sign)
    if 0 not in sign[1:]: break
    
if 0 in sign[1:]:
    print('No')
else:
    print('Yes')
    for s in sign[1:]:
        print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys
n,m = map(int, sys.stdin.readline().rstrip("\n").split())
cage = {}
for i in range (2,n+1):
    cage[i] = None
ab = [map(int, line.rstrip("\n").split()) for line in sys.stdin]
a,b = [list(i) for i in zip(*ab)]
room = [1]
nroom = []
while None in cage.values():
    for i in range(len(room)):
        j = 0
        while j < (len(a)):
            if a[j] == room[i]:
                if cage[b[j]] == None:
                    cage[b[j]] = a[j]
                nroom.append(b[j])
                a.pop(j)
                b.pop(j)
            elif b[j] == room[i]:
                if cage[a[j]] == None:
                    cage[a[j]] = b[j]
                nroom.append(a[j])
                a.pop(j)
                b.pop(j)
            else:
                j += 1
    room = nroom[:]
    nroom.clear()
    if len(a) == 0 and None in cage.values():
        print('No')
        break
else:
    print('Yes')
    for i in range (2,n+1):
        print(cage[i])

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
R = [[] for i in range(N) ]
ans = [-1 for i in range(N)]
rem = list(range(N))
flag = 1

for i in range(M):
    A, B = map(int, input().split())
    R[A - 1].append(B - 1)
    R[B - 1].append(A - 1)
    if A == 1:
        ans[0] = B - 1
    if B == 1:
        ans[0] = A - 1
#print(R)

d = [[] for i in range(N+1)]
d[0] = [0]

for i in range(N):
    #print(len(d[i]), d[i])
    if -1 not in ans:
        #print("break")
        flag = 0
        break
    for j in range(len(d[i])):
        r = []
        for k in rem:
            #print("k", k, R[k], rem, d[i][j])
            if d[i][j] in R[k]:
                ans[k] = d[i][j] + 1
                d[i+1].append(k)
                #print(R[k])
                if k in rem:
                    r.append(k)
        #print("r", r)
        for l in range(len(r)):
            rem.remove(r[l])
            
if flag == 1:
    print("No")
else:
    print("Yes")
    [print(i) for i in ans[1:]]

Submission status: Time Limit Exceeded

Solution code:
import sys

N, M = map(int, sys.stdin.readline().split())

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

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
    
sign_list = dijkstra(0,N,M,cost)
flag = True
for i in range(N - 1):
    if sign_list[i] == 0:
        flag = False
        break

if flag:
    print('Yes')
    for i in range(N - 1):
        print(sign_list[i])
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(m)]
ans = [-1] * n
ans[0] = 0
l = [1]

for _ in range(n):
    if l ==[]:
        break
    tmp = set()
    while l!=[]:
      now = l.pop()
      for i in range(m):
          x = a[i][0]
          y = a[i][1]
          if now==x and ans[y-1]==-1:
              ans[y-1]=now
              a[i][0]= a[i][1]=-1
              tmp.add(y)
          if now==y and ans[x-1]==-1:
              ans[x-1]=now
              a[i][0]= a[i][1]=-1
              tmp.add(x)
    l+=tmp
if -1 in a:
  print('No')
else:
  print('Yes')
  for i in range(1, n):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, defaultdict


def bfs(graph, start, ans_list):

    queue = deque([start])
    visited = set()
    distance = defaultdict(int)
    distance[start] = 0
    while queue:
        current_vertex = queue.popleft()
        visited.add(current_vertex)
        for v in graph[current_vertex]:
            if v not in visited and v not in queue:
                queue.append(v)
                ans_list[v] = current_vertex
    return ans_list

N, M = map(int, input().split())
paths = [tuple(map(int, input().split())) for _ in range(M)]

graph = defaultdict(set)
for A, B in paths:
    graph[A].add(B)
    graph[B].add(A)

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

ans_list = bfs(graph, 1, ans_list)

print('Yes')
for x in ans_list.values():
    print(x)

Submission status: Time Limit Exceeded

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

N ,M = map(int, input().split())
edge = np.array([input().split() for _ in range(M)], dtype = np.int64).T
a = np.ones((1,M))
edge = np.vstack([edge,a])

graph = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))

distance_mat, processors = shortest_path(graph,unweighted=True, directed = False, indices = 0, return_predecessors = True)

print("Yes")
processors = list(processors)
[print(i+1) for i in processors[1:]]

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
room, route_count = map(int,input().split())
route = np.array([list(map(int,input().split())) for _ in range(route_count)])
 
object_nums = [1]
ans = np.array([0]*(room-1))
 
def mem_ans(ans, object_num, next_nums):
    for n in next_nums:
        if ans[n-2] == 0:
            ans[n-2] = object_num
    return ans
 
for object_num in object_nums:

    object_rows = route[np.any(route==object_num, axis=1)]
    route[np.any(route==object_num, axis=1)] = 0
    next_nums = object_rows[object_rows!=object_num]
    if next_nums is not None:
        ans = mem_ans(ans, object_num, next_nums)
        object_nums.extend(next_nums)
    else:
        break
 
if 0 in set(ans):
  print('No')
else:
  print('Yes')
  for i in ans:
    print(i)

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)]
not_patrolled = set(range(1, N))

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

while len(queue) > 0:
  cur = queue.popleft()
  for i in not_patrolled.copy():
    c = adj[cur][i]
    if c == 1:
      queue.append(i)
      signs[i] = cur
      not_patrolled.remove(i)

if len(not_patrolled) == 0:
  print("Yes")
  for sign in signs[1:]:
    print(sign + 1)
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2*100000)
n, m = map(int,input().split())
mark = [-2] * (n-1)
dist = [0] * (n-1)
path = [[] for _ in range(n-1)]
path0 = []

def search(i):
    d = dist[i]
    p = []
    for p in path[i]:
        if dist[p] > d + 1 or dist[p] == 0:
            dist[p] = d + 1
            mark[p] = i
            search(p)

for _ in range(m):
    a, b = map(lambda x: int(x)-2, input().split())
    if a == -1:
        path0.append(b)
        dist[b] = 1
        mark[b] = -1
    elif b == -1:
        path0.append(a)
        dist[a] = 1
        mark[a] = -1
    else:
        path[a].append(b)
        path[b].append(a)

for p in path0:
    search(p)

print("Yes")
for i in mark: print(i+2)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
N,M = [int(i) for i in input().split()]
roads = []
for _ in range(M):
    A,B = [int(i) for i in input().split()]
    roads.append([A,B])
    roads.append([B,A])
roads = np.array(roads)
places = [0]*(N+1)
places[1] = 1
q = deque([1])
n = 1
while n < N:
    i = q.pop()
    L = roads[roads[:,0] == i][:,1]
    for j in L:
        if places[j] == 0:
            places[j] = i
            q.appendleft(j)
            n += 1
print("Yes")
for i in range(2,N+1):
    print(places[i])

Submission status: Time Limit Exceeded

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
def dijkstra(startNode, nodeNum, edgeNum, cost):
    '''
    startNodeから各頂点への最短距離をダイクストラ法で計算
    startNode:始点
    nodeNum:ノードの数
    edgeNum:エッジの数
    cost[a][b]:ab間の距離
    '''
    d = [float('inf')]*nodeNum
    x = [0]*nodeNum
    usedNode = [False]*nodeNum
    d[startNode] = 0
    
    while True:
        v = -1
        y = 0
        for i in range(n):
            if (not usedNode[i]) and (v == -1):
                v=i
                y=i+1
            elif (not usedNode[i]) and d[i] < d[v]:
                v=i
                y=i+1
        if v == -1:
            break
        usedNode[v] = True

        for j in range(n):
            if d[j] > d[v]+cost[v][j]:
                d[j] = d[v]+cost[v][j]
                x[j] = y
    return d,x


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

c = [[float('inf') for i in range(n)] for j in range(n)]
for i in range(m):
    c[a[i-1]-1][b[i-1]-1] = 1
    c[b[i-1]-1][a[i-1]-1] = 1

d,x = dijkstra(0, n, m, c)

print('Yes')
for i in range(n-1):
    print(x[i+1])

Submission status: Time Limit Exceeded

Solution code:
import copy

s = input().split()

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


ll = [set() for j in range(n + 1)]
sl = set()

s1 = {1}
s2 = set()


for i in range(m):
    t = input().split()
    sl.add(int(t[0]))
    sl.add(int(t[1]))
    ll[int(t[0])].add(int(t[1]))
    ll[int(t[1])].add(int(t[0]))


if sum(sl) < int(((n + 1) * n ) / 2):
    print("No")
    #print(sl,int(((n + 1) * n ) / 2))
else:
    count = 0
    goal = [0 for i in range(n)]
    out = 0

    while 1:
        s2.clear()
        out += 1
        for i in range(1,n+1):
            if len(s1 & ll[i]) != 0:
                s3 = list(s1 & ll[i])
                #print(s3)
                goal[i-1] = s3[0]
                s2.add(i)
                count += 1
                ll[i].clear()
        s1 = copy.deepcopy(s2)
        #print(s1,s2)

        if out >= 2000 or count >= n:
            break
    print("Yes")
    for i in range(1,n):
        print(goal[i])

    #print(count,out)
    #print(goal)

Submission status: Time Limit Exceeded

Solution code:
import queue

def dijkstra(g,node_count,start_index):

    INF = 10**9+7
    node = [INF] * node_count
    conf = [0] * node_count
    root = [-1] * node_count

    q = queue.Queue()
    q.put(0)
    root[0] = 0
    while not q.empty():

        p = q.get()
        conf[p] = 1
        for i in range(node_count):
            if root[i] < 0 and g[p][i] > 0 and i != p:
                q.put(i)
                root[i] = p

    return root


n, m = map(int, input().split())
r = []
#g = np.zeros((n,n))
g = [[0] * n for i in range(n)]

for i in range(m):
    a, b = map(int, input().split())
    g[a-1][b-1] = 1
    g[b-1][a-1] = 1
    #r.append([a,b])
#for i in range(n):
#    print(g[i])
#c = dijkstra_heapq(g,n,0)
#print(c)
c = dijkstra(g,n,0)

#c = np.array(c) + 1
#print(c)
ans = []
for i in range(1,n):
    if c[i] >= 0:
        ans.append(c[i]+1)
    else:
        print('No')
        exit()

print('Yes')
for i in range(len(ans)):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
sys.setrecursionlimit(10**6)

def main():
    n,m=map(int,input().split())
    graph=[[] for _ in range(n)]
    seen=[False]*n

    for _ in range(m):
        a,b=map(int,input().split())
        graph[a-1].append(b-1)
        graph[b-1].append(a-1)
    ans=[-1]*n
    q=deque([0])
    while len(q):
        now=q.popleft()
        seen[now]=True
        for i in graph[now]:
            if seen[i]:
                continue
            q.append(i)
            if ans[i]==-1:
                ans[i]=now
    print("Yes")
    for i in range(1,n):
        print(ans[i]+1)

if __name__=="__main__":
    main()

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
from collections import deque
def run():
    N, M = map(int, sysread().split())
    to = [[] for _ in range(N+1)]
    AB = list(map(int, read().split()))
    A = AB[::2]
    B = AB[1::2]
    for a,b in zip(A,B):
        to[a].append(b)
        to[b].append(a)

    seen = [False] * (N+1)
    queue = deque([])
    seen[1] = True
    queue.append((1, 0))# (node, prev)
    mark = [0] * (N+1)

    while queue:
        current, prev = queue.popleft()
        if not seen[current]:
            seen[current] = True
            mark[current] = prev
        for next in to[current]:
            if not seen[next]:
                queue.append((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:
#!/usr/bin/python3

import numpy
#標準出力からの読み込み
input_1 = input()
n = int(input_1.split(" ")[0])
m = int(input_1.split(" ")[1])

road = []
for i in range(m):
    input_m = input()
    road.append(int(input_m.split(" ")[0]))
    road.append(int(input_m.split(" ")[1]))

#判定ロジック

list_a = [i for i, x in enumerate(road) if x == 4]
output = ['' for s in range(n)]
output[0] = 'Yes'

def mark_maker(road, room_list, output):
    next_room_list = []
    for room in room_list:
        tmp_rooms_index = [i for i, x in enumerate(road) if x == room]
        next_rooms_index = list(map(lambda x: x+1 if x%2==0 else x-1, tmp_rooms_index))
        next_rooms = [road[j] for j in next_rooms_index]
        for k in next_rooms:
            if k == 1:
                continue
            if output[k-1] == '':
                output[k-1] = room
                next_room_list.append(k)
    return output, next_room_list

room_list = [1]
for i in range(100000):
    output, room_list = mark_maker(road, room_list, output)

if '' in output:
    print('No')
    exit()

for i in output:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse.csgraph import csgraph_from_dense, shortest_path
n, m, *AB = map(int, open(0).read().split())
graph = [[10**9]*n for _ in range(n)]
for a, b in zip(AB[::2], AB[1::2]):
    graph[a-1][b-1] = graph[b-1][a-1] = 1
G = csgraph_from_dense(graph, null_value=10**9)
d, p = shortest_path(G, indices=0, method='D', return_predecessors=1)
print('Yes')
print(*map(lambda x: int(x)+1, p[1:]), sep='\n')

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,astar_path
G = Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
N,M = map(int,input().split())
rows = [list(map(int,input().split())) for _ in range(M)]

G.add_edges_from(rows)

ans = ["Yes"]
for i in range(2,N+1):
    try:
        shortestPath = astar_path(G,source=i,target=1)
        ans.append(shortestPath[1])
    except:
        print("No")
        exit()

print(*ans,sep="\n")
# 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 LI():return list(map(int,input().split()))
def yes():print("Yes")
def no():print("No")
from collections import deque

def main():
    n,m=LI()
    edge=[[]*n for i in range(n)]
    for i in range(m):
        a,b=LI()
        a-=1;b-=1
        edge[a].append(b)
        edge[b].append(a)
    
    ans=[-1]*(n)
    goal=deque([0])
    while (-1 in ans):
        g=goal.popleft()
        for i in edge[g]:
            if ans[i]==-1:
                ans[i]=g+1
                goal.append(i)
    yes()
    print(*ans[1:])
main()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop

INT_MAX = 10 ** 9


def main():
  n, m = map(int, input().split())
  ab = (map(int, input().split()) for i in range(m))
  
  g = [[0] * (n+1) for i in range(n+1)]
  gp = [INT_MAX] * (n+1)
  gf = [0] * (n+1)
  
  for a, b in ab:
    g[a][b] = 1
    g[b][a] = 1
  
  h = [(0, 1, 1)]
  
  while h:
    p, a, b = heappop(h)
    if p < gp[a]:
      gp[a] = p
      gf[a] = b
    else:
      continue
    for z in range(1, n+1):
      if g[a][z]:
        heappush(h, (p + g[a][b], z, a))
  
  r = gf[2:]
  s = 'Yes' if all(0 < i < INT_MAX for i in r) else 'No'
  print(s)
  if s == 'Yes':
    for i in r:
      print(i)
  
  
  
if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict, deque
input = sys.stdin.readline
N, M = map(int, input().split())
guidepost = [None] * N
distance = [0] + [10**9] * (N - 1)
dd = defaultdict(list)
for _ in range(M):
    a, b = map(int, input().split())
    dd[a].append(b)
    dd[b].append(a)
stack = deque([1])
checked = [False] * N
while len(stack) >= 1:
    i = stack.popleft()
    checked[i - 1] = True
    for j in dd[i]:
        distance[j - 1] = min(distance[j - 1], distance[i - 1] + 1)
        if guidepost[j - 1] is None:
            guidepost[j - 1] = i
        elif distance[guidepost[j - 1] - 1] > distance[i - 1]:
            guidepost[j - 1] = i
        if not checked[j - 1]:
            stack.append(j)
print('Yes')
# join?
# for i in range(1, N):
#     print(guidepost[i])
print('\n'.join([str(guidepost[i]) for i in range(1, N)]))

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int,input().split())
l = [[0 for x in range(2)] for y in range(m)]
for i in range(m):
    l[i] = list(map(int,input().split()))
l2 = [m+1 for x in range(n)]
l2[0] = 1
l3 = [0 for x in range(n)]
key = 1
cnt = 0
while (cnt != n-1):
    for j in range(m):
        x1 = l[j][0]
        x2 = l[j][1]
        if l2[x1-1] == key:
            if key+1 < l2[x2-1]:
                l2[x2-1] = key + 1
                l3[x2-1] = l[j][0]
                cnt += 1
        elif l2[x2-1] == key:
            if key+1 < l2[x1-1]:
                l2[x1-1] = key+1
                l3[x1-1] = l[j][1]
                cnt += 1
    key += 1
print("Yes")
for k in range(n-1):
    print(l3[k+1])