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:
from scipy.sparse.csgraph import shortest_path
import numpy as np
import sys

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 = map(int, input().split())
A = []
B = []
neighbor = np.array([[0 for x in range(N)] for y in range(N)])
for i in range(M):
    a, b = map(lambda x: int(x)-1, input().split())
    neighbor[a][b] = 1
    neighbor[b][a] = 1

ans = []
for i in range(1,N):
    d, p = shortest_path(neighbor, return_predecessors=True, indices=[0, i])
    next_sign = get_path(0,i,p)
    if next_sign:
        ans.append(next_sign[-2]+1)
    else:
        print("No")
        sys.exit(0)

print("Yes")
for i in range(N-1):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from collections import deque
    n, m = map(int, input().split())
    michi = [[0 for i in range(n)] for j in range(n)]
    for _ in range(m):
        a, b = map(int, input().split())
        michi[a-1][b-1]=1
        michi[b - 1][a - 1] = 1
    heya=[-1]*n

    def f():
        check=0
        que = deque([])
        que.append(0)
        while que:
            if check==n-1:
                break
            else:
                p=que.popleft()
                for i in range(n):
                    if michi[p][i]==1 and heya[i]==-1:
                        michi[p][i]=0
                        michi[i][p]=0
                        heya[i]=p+1
                        check+=1
                        que.append(i)
        return

    f()
    print("Yes")
    for i in heya[1:]:
        print(i)
resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

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

distance = [-1] * n
prev = [-1] * n

q = deque()
q.append([0, 0, 0])  #[room, distance, prev]

while len(q) > 0:
    room, d, p = q.popleft()
    if distance[room] == -1:
        distance[room] = d
        prev[room] = p

    for n_room in adj_list[room]:
        if distance[n_room] > 0:
            continue
        q.append([n_room, d + 1, room])

flag = True
for i in range(n):
    if distance[i] < 0:
        flag = False
        break

if flag is True:
    print("Yes")
    for i in range(1, n):
        print(prev[i] + 1)
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)]

r=[[]*n for _ in range(n)]
f=[True]*n
d=[0]
b=[n+1]*n

for i in a:
    r[i[0]-1].append(i[1]-1)
    r[i[1]-1].append(i[0]-1)

o=0
#print(r[now][0])

b[o]=0
#print(now)
for _ in range(n):
    for i in r[o]:
        #i=r[now][j]
        if(b[i]==n+1):
            b[i]=o
            d.append(i)
    if(d):
        o=d[0]
        del d[0]

f=0
for i in b[1:]:
    if(i==n+1):
        f=1
if (f==0):
    print("Yes")
    for i in b[1:]:
        print(i+1)
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

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

arr2=[0]*n
for i in range(n):
    tmp=[]
    for j in range(n):
        if arr[i][j]==1:
            tmp.append(j)
    arr2[i]=tuple(tmp)
    if len(arr2[i])==0:
        print('No')
        sys.exit()


def bfs(d):
    que=deque()
    que.append(0)
    ans=[0]*n
    while que:
        x=que.popleft()
        if x==0:
            for j in range(n):
                if arr[0][j]==1:
                    ans[j]=1
                    que.append(j)
        else:
            for i in arr2[x]:
                if ans[i]==0 and i!=0:
                    ans[i]=x+1
                    que.append(i)
    print('Yes')
    for i in range(1,n):
        print(ans[i])        

bfs(arr)

Submission status: Time Limit Exceeded

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

n, m = [int(x) for x in input().split()]
g = [[] for _ in range(n)]

for _ in range(m):
    a, b = [int(x) for x in input().split()]
    g[a-1].append(b-1)
    g[b-1].append(a-1)
tmp = []
ans = [0]*n
ans2 = [0]
t = 0
while t < n:
  for s in ans2:
    for i in range(1,n):
      if s in g[i] and ans[i] == 0:
        tmp.append(i)
        ans[i] = s+1
  ans2 = tmp
  t += 1
if ans.count(0) == 1:
  print('Yes')
  for i in range(1,n):
    print(ans[i])
else:
  print('No')

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

ans=[-1]*n
goal=deque([0])
while goal:
    g=goal.popleft()
    for i in range(n):
        v=edge[i]
        if g in v:
            ans[i]=g
            edge[i].clear()
            goal.append(i)

if -1 in ans:
    no()
    exit()
yes()
for i in ans[1:]:
    print(i+1)

Submission status: Time Limit Exceeded

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

siru=[-1]*(N-1)#2~~N
que=[0]

while len(que)>0:
    #print(que)
    now=que.pop(0)
    nexlist=G[now]
    for nex in nexlist:
        if nex==0:
            continue
        if siru[nex-1]==-1:
            siru[nex-1]=now
            que.append(nex)
X=siru.count(-1)
if X>=1:
    print("No")
else:
    print("Yes")
    for num in siru:
        print(num+1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
import sys

sys.setrecursionlimit(10**5)

class DFS():
    def __init__(self,A_B_arr,N,M):
        self.N = N
        self.M = M
        self.route = {i:[] for i in range(N+1)}
        for A, B in A_B_arr:
            self.route[A].append(B)
            self.route[B].append(A)

        self.dp = [[None,N] for i in range(N+1)]
        self.dp[1] = [1,0]

    def dfs(self,i,rank):
        for r in self.route[i]:
            if rank<self.dp[r][1] and rank<self.N:
                self.dp[r] = [i,rank]
                self.dfs(r,rank+1)
        return


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    N, M = list(map(int,_in[0].split(' ')))  # type:list(int)
    A_B_arr = []
    for i in range(M):
        _ = list(map(int,_in[i+1].split(' ')))  # type:list(int)
        A_B_arr.append(_)
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    dfs = DFS(A_B_arr,N,M)
    dfs.dfs(1,1)

    ans = []
    TF = 'Yes'
    for (i,_) in enumerate(dfs.dp):
        if i>1:
            if _[0] == None:
                TF = 'No'
                break
            else:
                ans.append(_[0])
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    if TF == 'Yes':
        print(TF)
        for _ in ans:
            print(_)
    else:
        print(TF)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
edge = [[] for i in range(n+1)]
reached = [0 for _ in range(n+1)]
guide = {i: 0 for i in range(2, n+1)}
for _ in range(m):
    a, b = map(int, input().split())
    edge[a].append(b)
    edge[b].append(a)

# print(edge)
queue = [(e, 1) for e in edge[1]]
while len(queue) > 0:
    # print(queue)
    e, now = queue.pop(0)
    if reached[e] == 0:
        reached[e] = 1
        guide[e] = now
        # edge[e].remove(now)
        for next in edge[e]:
            if next != 1 and reached[next] == 0:
                queue.append((next, e))

print("Yes")
for i in range(2, n+1):
    print(guide[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, source=n, target=1)
        ans.append(preans[1])
    for n in ans:
      print(n)
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import heapq
def dijkstra_heap(s):
    #始点sから各頂点への最短距離
    d = [float("inf")] * (n)
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge[1]]:
            continue
        v = minedge[1]
        d[v] = minedge[0]
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,[e[0]+d[v],e[1]])
    return d
  
n,w = map(int,input().split()) #n:頂点数　w:辺の数

edge = [[] for i in range(n)]
G = [[] for i in range(n+1)]
#edge[i] : iから出る道の[重み,行先]の配列
for i in range(w):
    x,y = map(int,input().split())
    G[x].append(y)
    G[y].append(x)
    x = x - 1
    y = y - 1
    edge[x].append([1,y])
    edge[y].append([1,x]) 
ans = [0 for i in range(n+1)]
s = [[] for j in range(n)]
i = 1
for d in dijkstra_heap(0):
    s[d].append(i)
    i += 1
for i in s[1]:
    ans[i] = 1
for i in range(2,n):
    for t in s[i]:
        for j in s[i-1]:
            if t in G[j]:
                ans[t] = j
                break
print('Yes')
for i in range(2,n+1):
    print(ans[i])

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

################################
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)
path = [list(map(int,input().split())) for i in range (w)]
for i in range(w):
    x = path[i][0]-1
    y = path[i][1]-1
    cost[x][y] = 1
    cost[y][x] = 1
k = dijkstra(0,n,w,cost)
k.append(float('inf'))
#print(k)
torch = [n]*n
#print(torch)
for i in range(w):
    x = path[i][0]-1
    y = path[i][1]-1
    #print(x,y)
    #print(torch[x],torch[y])
    #print(k[x],k[y],k[torch[x]],k[torch[y]])
    if k[torch[x]] >k[y]:
        torch[x] = y
    if k[torch[y]] >k[x]:
        torch[y] = x
    #print(torch)
print('Yes')
for i in range(1,n):
  print(torch[i]+1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
N,M = map(int,input().split())

A = []
B = []

for x in range(M):
    At,Bt = map(int,input().split())
    A.append(At)
    B.append(Bt)
rinsetu =[[0 for x in range(N)] for y in range(N)]
for x in range(M):
    rinsetu[A[x]-1][B[x]-1] = 1
    rinsetu[B[x]-1][A[x]-1] = 1
L = csr_matrix(rinsetu)
shortest,p =  shortest_path(L,return_predecessors=True,indices=0)

print("Yes")
for x in p[1:]:
    print(x+1)

Submission status: Time Limit Exceeded

Solution code:
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


 
size = len(route)
cost = [INF for _ in range(size)]
visit = [NOT_VISITED for _ in range(size)]
before = [None for _ in range(size)]
cost[0] = 0
while True:
    min = INF
    for i in range(size):
        if visit[i] == NOT_VISITED and cost[i] < min:
            x = i
            min = cost[x]
    if min == INF:
        break
    visit[x] = VISITED
    #print("visited to {}.".format(chr(65+x)))
 
    for i in range(size):
        if cost[i] > route[x][i] + cost[x]:
            cost[i] = route[x][i] + cost[x]
            before[i] = x
 
before.pop(0)

if None in before:
    print("No")
    exit()
 
i = size - 1

print("Yes")


for i in before:
    print(i+1)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
L = [[0] * N for i 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
ans = [0] * N
from queue import Queue
q = Queue()
for i in range(N):
    if L[0][i] == 1:
        ans[i] = 1
        q.put(i)
while not q.empty():
    k = q.get()
    for i in range(1,N):
        if L[k][i] == 1:
            if ans[i] == 0:
                ans[i] = k+1
                q.put(i)
flag = True
for i in range(1,N):
    if ans[i] == 0:
        flag = False
        print('No')
        break
if flag == True:
    print('Yes')
    for i in range(N-1):
        print(ans[i+1])

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
if all(i>=0 for i in ans[1:]):
  print('Yes')
  for i in ans[1:]:
    print(i) 
else:
  print('No')

Submission status: Time Limit Exceeded

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

N,M = map(int,input().split())
Map = np.array([np.array([0]*N) for i in range(N)])

for i in range(M):
  a,b = map(int,input().split())
  a,b = a-1,b-1
  Map[a][b] = 1
  Map[b][a] = 1
  
d,p = shortest_path(Map,indices=0, return_predecessors=True, directed=False, unweighted=True)
judge = 1 
ans = ''
for i in range(1,N):
  if(i != N-1):
     ans += str(p[i]+1)+'\n'
  else:
     ans += str(p[i]+1)   
  
  if(p[i]<0):
     judge = 0
     break

if(judge == 0):
  print('No')
else:
  print('Yes')
  print(ans)

Submission status: Time Limit Exceeded

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

p=[0]*n
p[0]=1
now=1
cnt=1
k=10**8
while 0 in p and k>0:
    for to in l[now-1]:
        if p[to]==0:
            p[to]=now
    now=to+1
    cnt+=1
    k-=1
if 0 in p:
    print("No")
else:
    print("Yes")
    for i in range(1,n):
        print(p[i])

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]:
      if Y[j]==0:
        Y[j]=i+1
        note=note+[j]
  item=copy.deepcopy(note)
print("Yes")
for i in Y:
  if i==-1:
    continue
  print(i)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰回数の上限を変更
from collections import deque
N,M=map(int,input().split())
G=[[]for _ in range(N)]

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

dist=[10**5+10 for _ in range(N)]
chk=[0 for _ in range(N)]
dist[0]=0
prev=[-1 for _ in range(N)]


que=deque()
que.append((0,-1))

while(len(que)):
    v,p=que.popleft()
    if p==-1:
        pass
    else:
        val=dist[p]+1
        if val<dist[v]:
            dist[v]=val
            prev[v]=p
    chk[v]=1
    for tmp in G[v]:
        if tmp==p:
            continue
        if chk[tmp]==1:
            continue
        que.append((tmp,v))

print("Yes")
#print(dist)
for i in range(N):
    if i==0:
        continue
    print(prev[i]+1)

Submission status: Time Limit Exceeded

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


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]

n, m = map(int, input().split())
g = Graph()
for i in range(m):
    a, b = map(int, input().split())
    g.add_edge(a-1, b-1, 1)
    g.add_edge(b-1, a-1, 1)

d = Dijkstra(g, 0)
A = []
for i in range(n):
    a = d.shortest_distance(i)
    if a == float('inf'):
        print("No")
        break
    else:
        A.append(d.shortest_distance(i))

if len(A) == n:
    ANS = [0] * n
    for i in range(1, n):
        if ANS[i] == 0:
            B = d.shortest_path(i)
            ANS[B[-1]] = B[-2] + 1
    print("Yes")
    for i in ANS[1:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
g = {}
for i in range(M):
  a, b = map(int, input().split())
  if a in g.keys():
    g[a].append(b)
  else:
    g[a] = [b]
  if b in g.keys():
    g[b].append(a)
  else:
    g[b] = [a]
ans = [0 for _ in range(N+1)]
#print(g)
tmp = [1]
import time
start = time.time()
flag = True
while 0 in ans[2:]:
  #print(ans)
  for i in tmp:
    #print('i',i)
    next = g[i]
    #print('next',next)
    for j in next:
      if ans [j] == 0:
        ans[j] = i
  tmp = next
  if time.time() - start > 1.99:
    flag = False
    print('No')
    break
if flag:
  print('Yes')
  for i in range(2,N+1):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
path = [[] for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    path[a-1].append(b-1)
    path[b-1].append(a-1)
visited = [-1] * n
ans = [-1] * n
queue = deque([0])
while queue:
    pos = queue.popleft()
    visited[pos] = 1
    l = path[pos]
    for i in range(len(l)):
        if visited[l[i]] == -1:
            if ans[l[i]] == -1:
                ans[l[i]] = pos + 1
            queue.append(l[i])
print("Yes")
for i in range(1, n):
    print(ans[i])

Submission status: Time Limit Exceeded

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

ab = []
ans = {1:[1,0]}
now = [1]
next = []

for i in range(m):
    ab.append(list(map(int, input().split())))

while 1:
    for j in now:
        long = len(ab)
        for i in range(len(ab)):
            i = long - i - 1
            if j in ab[i]:
                if ab[i][0] == j:
                    ans.setdefault(ab[i][1], [ab[i][0], ans[ab[i][0]][1] + 1])
                    if ans[ab[i][1]][1] > ans[ab[i][0]][1] + 1:
                        ans[ab[i][1]][1] = ans[ab[i][0]][1] + 1
                    next.append(ab[i][1])
                    ab.pop(i)

                else:
                    ans.setdefault(ab[i][0], [ab[i][1], ans[ab[i][1]][1] + 1])
                    if ans[ab[i][0]][1] > ans[ab[i][1]][1] + 1:
                        ans[ab[i][0]][1] = ans[ab[i][1]][1] + 1
                    next.append(ab[i][0])
                    ab.pop(i)

    now.clear()
    if len(next) == 0:
        break
    now = next.copy()
    next.clear()

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

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



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

    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

        # print(v)

        for j in range(n):
            if d[j] > d[v] + cost[v][j]:
                d[j] = d[v] + cost[v][j]
                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 = [int(x) for x in input().split()]
path = []
for i in range(M):
  t1, t2 = [int(x) for x in input().split()]
  path.append((t1, t2))
l = [1]
ans = [1] + [0] * (N-1)
while True:
  t = l.pop(0)
  for i in reversed(range(len(path))):
    if t in path[i]:
      if path[i][0] == t:
        if ans[path[i][1]-1] == 0:
          ans[path[i][1]-1] = t
          l.append(path[i][1])
      else:
        if ans[path[i][0]-1] == 0:
          ans[path[i][0]-1] = t
          l.append(path[i][0])
      path.pop(i)
  if path == []:
    break
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())

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

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

distance = [-1] * n
prev = [-1] * n

q = deque()
q.append([0, 0, 0])  #[node, distance, prev]

while len(q) > 0:
    room, d, p = q.popleft()
    #if distance[room] > 0:
    #    continue
    if distance[room] == -1 or distance[room] > d:
        distance[room] = d
        prev[room] = p

    for n_room in adj_list[room]:
        if distance[n_room] > 0:
            continue
        q.append([n_room, d + 1, room])

flag = True
for i in range(n):
    if distance[i] < 0:
        flag = False
        break

if flag is True:
    print("Yes")
    for i in range(1, n):
        print(prev[i] + 1)
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

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 = map(int, input().split())
data = []
row = []
col = []
for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    data.append(1)
    row.append(a)
    col.append(b)
    data.append(1)
    row.append(b)
    col.append(a)
graph = csr_matrix((data, (row, col)), shape=(n, n))
_, p = dijkstra(graph, return_predecessors=True, directed=False, unweighted=True, indices=0)
for item in p[1:]:
    if(item < 0):
        print("No")
        exit()
print("Yes")
for item in p[1:]:
    print(item + 1)

Submission status: Time Limit Exceeded

Solution code:
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

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

idx = [0]
j = 0
while j < len(idx):
  for i in range(M):
    if AB[i][0] == idx[j] and miti[AB[i][1]] == 0:
      ikikata[AB[i][1]] = 1
      miti[AB[i][1]] = idx[j] + 1
      if AB[i][1] in idx:
        continue
      idx.append(AB[i][1])
    if AB[i][1] == idx[j] and miti[AB[i][0]] == 0:
      ikikata[AB[i][0]] = 1
      miti[AB[i][0]] = idx[j] + 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(i)

Submission status: Time Limit Exceeded

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

import sys

input = sys.stdin.readline
R = [[]]*n
Sin = [-1]*n
Dis = [-1]*n
Sin[0] = 0
Dis[0] = 0

for _ in range(m):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  R[a] = R[a] + [b]
  R[b] = R[b] + [a]
  
#print(R)

from collections import deque

d = deque()
d.append(0)

while len(d):
  cur = d.popleft()
  for to in R[cur]:
    if to == Sin[cur] -1:
      continue
    if Dis[to]<0:
      Dis[to] = Dis[cur] + 1
      Sin[to] = cur + 1
      d.append(to)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from scipy.sparse.csgraph import csgraph_from_dense, dijkstra
import numpy as np

input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)


def main():
    N, M = map(int, input().split())
    F = [[0 for i in range(N)] for j in range(N)]

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

    G = csgraph_from_dense(F, null_value=0)
    d, predecessors = dijkstra(G, return_predecessors=True)
    # print(d, "\n", predecessors)

    # print(type(G))
    if np.any(d[0] == np.inf):
        print("No")
        sys.exit()
    else:
        print("Yes")
        for i in range(1, N):
            print(predecessors[0][i] + 1)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n,m=map(int,input().split())
a=[tuple(map(int,input().split())) for i in range(m)]

d=deque([(1,0)])
checked=[0]*n
checked[0]=1
ans=[0]*(n-1)
while len(d)>0:
    rm,dep=d.popleft()
    for i in a:
        if i[0]==rm or i[1]==rm:
            if checked[i[i.index(rm)-1]-1]==0:
                d.append((i[i.index(rm)-1],dep+1))
                checked[i[i.index(rm)-1]-1]=1
                ans[i[i.index(rm)-1]-2]=rm
print('Yes')
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from queue import Queue

N, M = list(map(int, input().split()))
road_map = defaultdict(list)
for _ in range(M):
    a, b = list(map(int, input().split()))
    road_map[a].append(b)
    road_map[b].append(a)

reachable_room_map = {i + 1: 0 for i in range(N)}

reachable_room_map[1] = -1
q = Queue()
q.put([1])
while not q.empty():
    for room in q.get():
        roads = road_map[room]
        #  print("room: ", room, roads)
        for road in roads:
            if reachable_room_map[road] == 0:
                #  print(f"road {road} set as room {room}.")
                reachable_room_map[road] = room
                q.put(road_map[room])
            #  else:
                #  print(f"road {road} is already.")

#  print(reachable_room_map)
reachable_room_map.pop(1)
if all([v != 0 for v in reachable_room_map.values()]):
    print("Yes")
    for ans in reachable_room_map.values():
        print(ans)
else:
    print("No")