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 bisect,collections,copy,heapq,itertools,math,numpy,string
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
import sys
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def SS(): return map(str,sys.stdin.readline().rstrip().split())
def II(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())
 
 
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 i < 0:
        return []
    path.append(i)
    return path[::-1]
 
N,M = II()
#d = [[float("inf")]*N for i in range(N)] 
d = [[0]*N for i in range(N)]
for _ in range(M):
  A,B = II()
  d[A-1][B-1] = d[B-1][A-1] = 1
 
a,b = dijkstra(csr_matrix(d),return_predecessors=True)
  
#print(a)
path = [-1]*(N)
for i in range(1,N):
  tmp = get_path(i,0,b)
  #print("tmp=",tmp)
  now = i
  for j in range(1,len(tmp)):
    if path[now] == -1:
      path[now] = tmp[j]
      now = path[now]
    elif path[now] == tmp[j]:
      break
    else:
      print("No")
      exit()
print("Yes")
for i in range(1,N):
  print(path[i]+1)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
l = []
for i in range(M):
    l.append(list(map(int, input().split())))

matrix = [[0]*N for i in range(N)]
for i in range(M):
    matrix[l[i][0]-1][l[i][1]-1] = 1
    matrix[l[i][1]-1][l[i][0]-1] = 1
que = [0]
check = [0]*N

temp_l = [list(range(N)), [0]*N, [0]*N]

count = 0
while len(que) != 0:
    count += 1
    search = que.pop(0)
    for i in range(N):
        if matrix[search][i] == 1 and check[i] == 0:
            que.append(i)
            temp_l[1][i] = search
            temp_l[2][i] = count
            check[i] = 1

if 0 in temp_l:
    print('No')
else:
    print('Yes')
    for i in range(1, N):
        print(temp_l[1][i]+1)

Submission status: Time Limit Exceeded

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

a_s = []
b_s = []

for i in range(m):
    a, b = list(map(int,input().split()))
    a_s.append(a)
    b_s.append(b)

weight = [9999999] * (n + 1)
weight[1] = 1
joint_to = [0] * (n + 1)

for j in range(1, n+1):
    jointed_temp = []
    for i in range(m):
        if a_s[i] == j:
            jointed_temp.append(b_s[i])
        if b_s[i] == j:
            jointed_temp.append(a_s[i])
    joint_to[j] = sorted(jointed_temp)

def search_depth(joint_list, ind, weight_list, depth):
    for w in joint_list[ind]:
        depth_tmp = depth
        if weight_list[w] > depth:
            weight_list[w] = depth
            depth_tmp = depth_tmp + 1
            search_depth(joint_list, w, weight_list, depth_tmp)

torch_l = [0] * (n + 1)
def torch(joint_list, weight_list, torch_list):
    for i, dep in enumerate(weight_list, 0):
        if not i == 0:
            for j_to in joint_list[i]:
                if weight_list[j_to] == dep - 1:
                    torch_list[i] = j_to
                    break
                if j_to == 1:
                    torch_list[i] = 1
                    break

search_depth(joint_to, 1, weight, depth=2)
torch(joint_to, weight, torch_l)

flag_no = 0
for x in torch_l[2:]:
    if x == 0:
        print('No')
        flag_no = 1
        break
if flag_no == 0:
    print('Yes')
    for i in range(2, len(torch_l)):
        print(torch_l[i])

Submission status: Time Limit Exceeded

Solution code:
if __name__ == "__main__":
    n, m = map(int, input().split())

    nexts = [[]] * n
    
    for i in range(m):
        ai, bi = map(int, input().split())
        ai -= 1
        bi -= 1
        if len(nexts[ai]) == 0:
            nexts[ai] = [bi]
        else:
            nexts[ai].append(bi)
        if len(nexts[bi]) == 0:
            nexts[bi] = [ai]
        else:
            nexts[bi].append(ai)

    scores = [m] * m
    scores[0] = 0

    red_set = [0]
    new_red_set = []
    blue_set = [x + 1 for x in range(n - 1)]
    new_blue_set = blue_set

    arrows = [0] * n

    j = 0

    while len(blue_set) != 0:
        for r in red_set:
            for nxt in nexts[r]:
                if nxt in blue_set:
                    new_blue_set.remove(nxt)
                    if nxt not in new_red_set:
                        new_red_set.append(nxt)
                    arrows[nxt] = r
                blue_set = new_blue_set

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# list(map(int, input().split()))
# int(input())

def main(AB, N, M):

    def serch(st = {1}, already = {1}, dict = {1:1}):
        next_dict = dict.copy()
        # for l in st:
        #     for i in [ab[0] if ab[1] == l else ab[1] for ab in AB if l in ab]:
        #         next_dict.setdefault(i, l)

        # next_dict.update({i:l for l in st for i in [ab[0] if ab[1] == l else ab[1] for ab in AB if l in ab]})

        # [next_dict.setdefault(i, l) for l in st for i in [ab[0] if ab[1] == l else ab[1] for ab in AB if l in ab]]
        # next_st = {k for k in next_dict if k not in already}

        next_dict.update({i:l for l in st for i in [ab[0] if ab[1] == l else ab[1] for ab in AB if l in ab] if i not in already})
        next_st = set(next_dict.keys())
        # [already.add(k) for k in next_st]
        next_already = already.union(next_st)
        if len(next_already) == N:
            return next_dict
        elif len(next_st) == 0:
            print('No')
            exit()
        else:
            return serch(next_st, next_already, next_dict)

    ans = serch()
    print('Yes')
    [print(ans[i + 1]) for i in range(1, N)]



if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = []
    for _ in range(M):
        AB.append(list(map(int, input().split())))
    main(AB, N, M)

Submission status: Time Limit Exceeded

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

N, M = map(int, readline().split())
ans = []
append_ans = ans.append
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]
append_q = q.append
checked = [0] * (N + 1)
checked[root] = 1
order = []
append_order = order.append
parent = [-1 for _ in range(N+1)]

while q:
    x = q.pop(0)
    for y in graph[x]:
        if checked[y]:
            continue
        if parent[y] != -1:
            continue
        parent[y] = x
        append_ans(x)
        append_order(y-2)
        checked[y] = 1
        append_q(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:
# a=input()
#N=int(input())
N,M=map(int,input().split(" "))
#a=[int(_) for _ in input().split(" ")]

A=[]
B=[]

n1=[0]*N #0 or 1
n1[0]=1
n2=[0]*N #前の部屋
n2[0]=1
n3=[] #次checkする値

#print(len(n3))

for i in range(M):
    a,b=map(int,input().split(" "))
    A.append(a)
    B.append(b)
    if a == 1:
        n1[b-1]=1
        n2[b-1]=1
        n3.append(b)
    if b == 1:
        n1[a-1]=1
        n2[a-1]=1
        n3.append(a)

while 0 in n1 and len(n3) != 0:
    n3t = n3
    #print(n3t)
    n3=[]
    for i in n3t:
        for j in range(1,M):
            if A[j] == i:
                n1[B[j]-1] = 1
                if n2[B[j]-1] > i or n2[B[j]-1] == 0:
                    n2[B[j]-1] = i
                n3.append(B[j])
            elif B[j] == i:
                n1[A[j]-1] = 1
                if n2[A[j]-1] > i or n2[A[j]-1] == 0:
                    n2[A[j]-1] = i
                n3.append(A[j])
    #print(n1)
    #print(n2)
    #print(n3)
    #n3=[]


ans=0
if 0 in n1:
    ans="No"

if ans != 0:
    print(ans)
else:
    print("Yes")
    for i in range(1,N):
        print(n2[i])

Submission status: Time Limit Exceeded

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

ans = [0]*N
pas = [M+1]*N
ans[0] = 1
pas[0] = 0

for i in range(M):
    if D[i][0] > D[i][1]:
        tmp = D[i][1]
        D[i][1] = D[i][0]
        D[i][0] = tmp
D.sort(key=lambda x:x[0])

for i in range(M):
    while ans[D[i][0]-1] == 0:
        D.append(D[i])
        D.pop(i)
    if pas[D[i][0]-1]+1 < pas[D[i][1]-1]:
        pas[D[i][1]-1] = pas[D[i][0]-1]+1
        ans[D[i][1]-1] = D[i][0]
    if pas[D[i][1]-1]+1 < pas[D[i][0]-1]:
        pas[D[i][0]-1] = pas[D[i][1]-1]+1
        ans[D[i][0]-1] = D[i][1]


if 0 not in pas[1:]:
    print('Yes')
    for n in ans[1:]:
        print(n)

else:
    print('No')

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

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

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 heapq


N,M=map(int, input().split())


UNVISITED = -1
INF         = 100000
VISITED     = 1
NOT_VISITED = 0


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


def dijkstra( adj, start, goal=None):
    '''
    ダイクストラアルゴリズムによる最短経路を求めるメソッド
    入力
    adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合，値はfloat('inf'))となるような2次元リスト(正方行列)
    start: 始点のID
    goal: オプション引数．終点のID
    出力
    goalを引数に持つ場合，startからgoalまでの最短経路を格納したリストを返す
    持たない場合は，startから各頂点までの最短距離を格納したリストを返す
    >>> d = Dijkstra()
    >>> d.dijkstra([[float('inf'), 2, 4, float('inf'), float('inf')], [2, float('inf'), 3, 5, float('inf')], [4, 3, float('inf'), 1, 4], [float('inf'), 5, 1, float('inf'), 3], [float('inf'), float('inf'), 4, 3, float('inf')]], 0)
    [0, 2, 4, 5, 8] # 例えば，始点0から頂点3までの最短距離は5となる
    >>> d.dijkstra([[float('inf'), 2, 4, float('inf'), float('inf')], [2, float('inf'), 3, 5, float('inf')], [4, 3, float('inf'), 1, 4], [float('inf'), 5, 1, float('inf'), 3], [float('inf'), float('inf'), 4, 3, float('inf')]], 0, goal=4)
    [0, 2, 4] # 頂点0から頂点4までの最短経路は0 -> 2 -> 4となる
    '''
    num = len(adj)          # グラフのノード数
    dist = [float('inf') for i in range(num)] # 始点から各頂点までの最短距離を格納する
    prev = [float('inf') for i in range(num)] # 最短経路における，その頂点の前の頂点のIDを格納する
    
    dist[start] = 0
    q = []                  # プライオリティキュー．各要素は，(startからある頂点vまでの仮の距離, 頂点vのID)からなるタプル
    heapq.heappush(q, (0, start)) # 始点をpush

    while len(q) != 0:
        prov_cost, src = heapq.heappop(q) # pop
        
        # プライオリティキューに格納されている最短距離が，現在計算できている最短距離より大きければ，distの更新をする必要はない
        if dist[src] < prov_cost:
            continue

        # 他の頂点の探索
        for dest in range(num):
            cost = adj[src][dest]
            if cost != float('inf') and dist[dest] > dist[src] + cost:
                dist[dest] = dist[src] + cost # distの更新
                heapq.heappush(q, (dist[dest], dest)) # キューに新たな仮の距離の情報をpush
                prev[dest] = src                      # 前の頂点を記録
                
    prev.pop(0)
    if goal is None:
        if float('inf') in prev:
            print("No")
        else:
            print("Yes")
            for i in prev:
                print(i+1)


def get_path( goal, prev):
    '''
    始点startから終点goalまでの最短経路を求める
    '''
    path = [goal]           # 最短経路
    dest = goal

    # 終点から最短経路を逆順に辿る
    while prev[dest] != float('inf'):
        path.append(prev[dest])
        dest = prev[dest]

    # 経路をreverseして出力
    return list(reversed(path))

dijkstra(route,0)

Submission status: Time Limit Exceeded

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

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)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, defaultdict
N, M = map(int, input().split())
D = [[float("inf")]*N for _ in range(N)]
for i in range(N):
    D[i][i] = 0
for i in range(M):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    D[s][t] = 1
    D[t][s] = 1

q = deque()
q.append(0)
d = defaultdict(lambda : int(-1))
d[0] = 0
while q:
    u = q.popleft()
    for v in range(N):
        if D[u][v] == float("inf"):
            continue
        if not d[v] == -1:
            continue
        d[v] = u
        q.append(v)
if len(d) == N:
    print("Yes")
else:
    print("No")
    exit()
for i in range(1, N):
    print(d[i]+1)

Submission status: Time Limit Exceeded

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

def main():
  N,M = map(int,input().split())
  path = [[] for i in range(N)]
  inf = 10 ** 6 * 2
  ans = [[None,inf] for i in range(N - 1)]
  
  for _ in range(M):
    a,b = map(int,input().split())
    a = a - 1
    b = b - 1
    path[a].append(b)
    path[b].append(a)
  
  def dfs(cur,par,con):
    if con == M + 1:
      return
    for chi in path[cur]:
      if chi == par:
        continue
      if con < ans[chi - 1][1]:
        ans[chi - 1][0] = cur
        ans[chi - 1][1] = con + 1
        dfs(chi,cur,con + 1)
  
  dfs(0,-1,0)
  
  if all([i[0] != None for i in ans]):
    print("Yes")
    for i in range(N - 1):
      print(ans[i][0] + 1)
  else:
    print("No")

if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N,M = map(int, input().split())
path = [[]*1 for i in range(N)]
for i in range(M):
    a = list(map(int, input().split()))
    path[a[0]-1].append(a[1])
    path[a[1]-1].append(a[0])
    #path.append( a )

#path = np.array(path)
'''
def connect(x):
    a1 = path[path[:,0]==x][:,1]
    a2 = path[path[:,1]==x][:,0]
    return list(np.concatenate([a1,a2]))
'''
#con = list(map(connect, range(1,N+1)))
con=path

#dangerous = list(range(2,N+1))
ans = np.zeros(N)
ans[0] = 0.5

layer = [1]
judge="Yes"

def find_next(layer):
    for room in layer:
        next_rooms = con[room-1]
        #next_rooms = np.array(list(set(next_rooms) & set(dangerous)))
        for r in next_rooms:
            if ans[r-1]==0:
                ans[r-1] = room
            #dangerous.remove(r)
    return next_rooms

while ans.min()==0:
    layer = find_next(layer)
    if len(layer)==0:
        judge = "No"
        break

if judge =="Yes":
    print(judge)
    for m in ans[1:]:
        print(int(m))
else:
    print(judge)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main():
    N, M = list(map(int, input().split()))
    R = [set() for _ in range(N+1)]
    for _ in range(M):
        x = list(map(int, input().split()))
        R[x[0]].add(x[1])
        R[x[1]].add(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 r[i] == 0 and i not in s and i not in q:
                r[i] = x
                if r.count(0) == 2:
                    print("Yes")
                    print("\n".join(map(str, r[2:])))
                    exit()
                else:
                    q.append(i)
    if len(s) == N:
        print("Yes")
        print("\n".join(map(str, r[2:])))
    else:
        print("No")

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
a,b=map(int,input().split())
List=[list(map(int,input().split())) for i in range(b)]
l=[0]*(a+1)
line=deque([1])
while line:
  i=line.popleft()
  bye=[]
  for j in range(len(List)):
    x,y=List[j]
    if x==i:
      if l[y]==0:
        l[y]=i
        bye+=[j]
        line.append(y)
    if y==i:
      if l[x]==0:
        l[x]=i
        bye+=[j]
        line.append(x)
  for p in range(len(bye)):
    List.pop(bye[p]-p)
print("Yes")
for h in range(a-1):
  print(l[h+2])

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())
    paths.add((a-1, b-1))

rooms = [-1] * N
rooms[0] = 0
marks = [-1] * (N-1)
key_rooms = [[0]]
for step in range(1, N):
    kick_list = []
    next_key_rooms = set()
    for key_room in key_rooms[-1]:
        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
                    next_key_rooms.add(else_room)
                    marks[else_room-1] = key_room
    key_rooms.append(next_key_rooms)
    for kick in kick_list:
        if kick in paths:
            paths.remove(kick)

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(M)]
Q = deque([1])
ans = [0]*N
while AB:
    i = Q.popleft()
    cnt = []
    for j in range(len(AB)):
        if AB[j][0] == i:
            if ans[AB[j][1]-1] == 0:
                ans[AB[j][1]-1] = i
            Q.append(AB[j][1])
            cnt.append(AB[j])
        elif AB[j][1] == i:
            if ans[AB[j][0]-1] == 0:
                ans[AB[j][0]-1] = i
            Q.append(AB[j][0])
            cnt.append(AB[j])
    for i in cnt:
        AB.remove(i)
print('Yes')
for i in range(1,N):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
import sys
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def SS(): return map(str,sys.stdin.readline().rstrip().split())
def II(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())


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 i < 0:
        return []
    path.append(i)
    return path[::-1]

N,M = II()
#d = [[float("inf")]*N for i in range(N)] 
d = [[0]*N for i in range(N)]
for _ in range(M):
  A,B = II()
  d[A-1][B-1] = d[B-1][A-1] = 1

a,b = dijkstra(csr_matrix(d),return_predecessors=True)
  
#print(a)
path = [-1]*(N)
for i in range(1,N):
  tmp = get_path(i,0,b)
  #print("tmp=",tmp)
  now = i
  for j in range(1,len(tmp)):
    if path[now] == -1:
      path[now] = tmp[j]
      now = path[now]
    elif path[now] == tmp[j]:
      now = path[now]
    else:
      print("No")
      exit()
print("Yes")
for i in range(1,N):
  print(path[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 = [(1, 1, 0)]
  
  while h:
    a, b, p = 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, (z, a, p + g[a][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:
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 visited[i]:
                continue
            else:
                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:
n,m=map(int, input().split())

#隣接リスト
adjacency_list=[[] for i in range(n)]
for i in range(m):
    a,b=map(int, input().split())
    adjacency_list[a-1].append(b-1)
    adjacency_list[b-1].append(a-1)

#i番目が、1からの距離がiのリスト
dist_list=[set([0])]
#i番目が、1から部屋までの距離
#dist_list2=[float("inf")]*n
#dist_list2[0]=0
#目印をつける方向
flag_list=[0]*(n-1)
#処理が終わってない部屋の集合
task_list=set([int(i) for i in range(1,n)])

tmp=[0]
while len(task_list)!=0:
    for i in tmp:
        #iはひとつ距離が短い部屋の番号
        tmp=set([])
        for j in adjacency_list[i]:
            #jは、iと隣接している部屋の番号
            if j in task_list:
            #if dist_list2[j] = float("inf"):
                #dist_list2[j]=#新しい距離
                tmp.add(j)
                flag_list[j-1]=i
                task_list.discard(j)
print("Yes")
for i in flag_list:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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]
  visited1 = []
  visited = {}
  for i in range(1,N+1):
    visited[i] = 0  
  miti = {}
  for i in range(1,N+1):
    miti[i] = 0
  while queue:
    label = queue.pop(0)
    for i in graph[label]:
      if visited[i] != 0:
        continue
      visited1.append(i)
      visited[i] = 1
      queue.append(i)
      if miti[i] != 0:
        return False
      miti[i] = label
    if len(visited1) == N:
      break
  if len(visited1) != N:
    return False
  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:
n, m = map(int, input().split())
l = [list(map(int, input().split())) for i in range(m)]
d = [0] + [100000]*(n-1)
a = [[float('inf') for j in range(n)] for i in range(n)]
t = [0]*n

for i in range(m):
    a[l[i][0]-1][l[i][1]-1] = 1
    a[l[i][1]-1][l[i][0]-1] = 1

for i in range(n):
    for j in range(n):
        if d[i] + a[i][j] < d[j]:
            d[j] = d[i] + a[i][j]
            t[j] = i+1
if 0 in t[1:]:
    print("No")
else:
    print('Yes')
    for i in range(1,n):
        print(t[i])