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.

Solution (Python):
print("Yes")
N, M = map(int, input().split())
path = [[] for _ in range(N)]
ind = [0 for _ in range(N)]
lis = [0] + [1 for _ in range(N-1)]
for i in range(M):
    A, B = map(int, input().split())
    path[A-1].append(B-1)
    path[B-1].append(A-1)
que = path[0]
for p in que:
    lis[p] = 0
for l in que:
    U = path[l]
    for m in U:
        if lis[m] ==1:
            ind[m] = l
            lis[m] = 0
            que.append(m)
    if lis == {}:
        break
for z in range(1,N):
    ind[z] += 1
    print(ind[z])

Solution (Python):
from collections import deque
import sys
sys.setrecursionlimit(200000)
N, M = map(int, input().split())
graph = [[] for j in range(N)]
q = deque([])
depth_array = [-1 for i in range(N)]

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

def bfs(graph, q, depth_array):
    
    if len(q) == 0:
        return depth_array

    cur_room = q.popleft()

    
    for r in graph[cur_room]:
        if depth_array[r] == -1: 
            q.append(r)
            depth_array[r] = depth_array[cur_room] + 1

    return bfs(graph, q, depth_array)
    

q.append(0)
depth_array[0] = 0
depth_array = bfs(graph, q, depth_array)

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


for room, depth in enumerate(depth_array):
    for node in graph[room]:
        if depth_array[node] + 1 == depth_array[room]:
            mark_array[room] = node

if -1 in mark_array[1:]:
    print("No")
else:
    print("Yes")
    for m in mark_array[1:]:
        print(m+1)

Solution (Python):
def resolve():
  N, M = map(int, input().split(" "))
  AB_map = [[] for i in range(N)]
  for m in range(M):
    AB = [int(x) - 1 for x in input().split(" ")]
    AB_map[AB[0]].append(AB[1])
    AB_map[AB[1]].append(AB[0])

  not_finished = set(range(1, N+1))
  rooms = [None] * N
  rooms[0] = 0
  room_depths = [0] * N

  recent_rooms = [0]
  depth = 1
  while len(not_finished) != 0 and depth < N:
    temp_recent = set()
    for r in recent_rooms:
      for target in AB_map[r]:
        if target in not_finished:
          temp_recent.add(target)
          not_finished.remove(target)
          rooms[target] = r
          room_depths[target] = depth
    depth += 1
    recent_rooms = list(temp_recent)

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

if __name__ == "__main__":
    resolve()

Solution (Python):
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append([a,b])


Edict = [[] for n in range(N+1)]
for e in E:
    Edict[e[0]].append(e[1])
    Edict[e[1]].append(e[0])

output = [0] + [0] + [BigM]*(N-1)
prev = [0 for n in range(N+1)]
prev_cnt = 0
now = [1]

prev[1] = 1
while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    for next in Edict[n]:
        if prev[next] == 0:
            output[next] = n
            now.append(next)
            prev[next] = 1

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Solution (Python):
import queue
N,M = map(int,input().split())
adj = [[]for i in range(N+1)]
parent = [-1] * (N+1) 
for m in range(M):
    a,b = map(int,input().split())
    adj[a].append(b)
    adj[b].append(a)
q = queue.Queue() 
q.put((1,0)) 
while(not q.empty()):
    x, p = q.get()
    if parent[x] != -1: 
        continue
    parent[x] = p
    for next in adj[x]:
        if parent[next] == -1: 
            q.put((next,x)) 
print ('Yes') 
for p in parent[2:]: 
    print(p)

Solution (Python):
n,m=map(int,input().split())
r=[[] for x in range(n)]
for c in range(m):
    a,b=map(int,input().split())
    r[a-1].append(b-1)
    r[b-1].append(a-1)
s=[-1]*n
s[0]=0
u=[0]
k=1
for c in range(10**5):
    v=[]
    for d in u:
        for e in r[d]:
            if s[e]==-1:
                s[e]=d
                k+=1
                v.append(e)
    if k>n-1:
        break
    u=v
print('Yes')
for c in s[1:]:
    print(c+1)

Solution (Python):

import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

n, m =MAP()
graph = defaultdict(set)
for _ in range(m):
    temp1, temp2 = MAP()

    graph[temp1].add(temp2)
    graph[temp2].add(temp1)

visited = [0]*(n+1)

q = deque()

q.append(1)
visited[1] = -1
while(q):
    popped = q.popleft()

    for child in graph[popped]:
        if(visited[child]==0):
            q.append(child)
            visited[child] = popped
visited = visited[2:]

if(0 in visited):
    print("No")
else:
    print("Yes")
    for el in visited:
        print(el)

Solution (Python):
import sys
def input():return sys.stdin.readline()[:-1]
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())
def LN(n):return [N() for i in range(n)]
def LL(n):return [L() for i in range(n)]
def YesNo(x):print("Yes")if x==True else print("No")
n,m=NM()
edge=[[] for i in range(n+1)]
for i in range(m):
    a,b=map(int,input().split())
    edge[a].append(b)
    edge[b].append(a)
pre=[-1]*(n+1)
from collections import deque
def bfs(s,n):
    d=[-1 for i in range(n+1)]
    d[s]=0
    q=deque([s])
    while q:
        x=q.popleft()
        for i in edge[x]:
            if d[i]==-1:
                d[i]=d[x]+1
                pre[i]=x
                q.append(i)
    return d
bfs(1,n)
if -1 in pre[2:]:
    print("No")
else:
    print("Yes")
    for i in pre[2:]:
        print(i)

Solution (Python):
import queue

N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(M):
    A, B = map(int, input().split())
    graph[A-1].append(B-1)
    graph[B-1].append(A-1)

up = [-1 for _ in range(N)]
up[0] = 0

q = queue.Queue()
q.put(0)
while not q.empty():
    now = q.get()
    for x in graph[now]:
        if up[x] != -1:
            continue
        up[x] = now
        q.put(x)

print('Yes')
for i in range(1, N):
    print(up[i]+1)

Solution (Python):
from collections import deque

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

q=deque([0])

TFl=[0]*N
TFl[0]=1
ml=[-1]*N

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

while q:
  p = q.popleft()
  for i in l[p]: 
    if TFl[i]==1:
      continue
    TFl[i]=1
    ml[i]=p
    q.append(i)

if all([i==1 for i in TFl]):
  print('Yes')
  for i in range(1, N):
    print(ml[i]+1)

else:
  print('No')

Solution (Python):
from sys import stdin
from collections import deque
input = stdin.readline


def main():
    n, m = map(int, input().split())

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

    blues = [-1] * n 
    blues[0] = 0 
    checked = [0] * n

    red_deque = deque([0])

    while len(red_deque) > 0:
        rd = red_deque[0]
        red_deque.popleft()
        if checked[rd] == 0:
            checked[rd] = 1
            for nxt in nexts[rd]:
                if blues[nxt] == -1:
                    blues[nxt] = rd
                    red_deque.append(nxt)

    print("Yes")
    for blue in blues[1:]:
        print(blue + 1)
    

if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque

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

nodes = {i: set() for i in range(n)}

for _ in range(m):
    a, b = map(int, input().split())
    nodes[a-1].add(b)
    nodes[b-1].add(a)

def bfs(r):
    queue = deque([r])
    ds = [None]*n
    ds[r-1] = 0
    while(queue):
        v = queue.popleft()
        for i in nodes[v-1]:
            if ds[i-1] == None:
                ds[i-1] = ds[v-1] + 1
                queue.append(i)
    return ds

ds = bfs(1)
for i in range(n):
    if i == 0:
        print("Yes")
    else:
        for j in nodes[i]:
            if ds[i]-1 == ds[j-1]:
                print(j)
                break

Solution (Python):
from collections import deque
n, m = map(int, input().split())
room_adjacent = [[] for _ in range(n)]
for _ in range(m):
  room1, room2 = map(int, input().split())
  room_adjacent[room1-1].append(room2)
  room_adjacent[room2-1].append(room1)

room_labels = [1]+[0]*(n-1)
old_room = 1
path_queue = deque((old_room, room) for room in room_adjacent[old_room-1])
while path_queue:
  old_room, new_room = path_queue.pop()
  if room_labels[new_room-1] == 0:
    room_labels[new_room-1] = old_room
    for another_room in room_adjacent[new_room-1]:
      path_queue.appendleft((new_room, another_room))
  
if 0 in room_labels:
  print("No")
else:
  print("Yes")
  [print(value) for value in room_labels[1:]]

Solution (Python):

from collections import deque

def bfs(graph, N, start):
    visited = [-1] * N
    visited[start] = 0
    que = deque([start])
    while que:
        node = que.popleft()
        for n in graph[node]:
            if visited[n] == -1:
                visited[n] = node
                que.append(n)
    return visited



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

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

visited = bfs(graph,N,0)

if -1 not in visited[1:]:
    print("Yes")
    for v in visited[1:]:
        print(v+1)
else:
    print("No")

Solution (Python):
from collections import deque

N, M = map(int, input().split())
AB = [map(int, input().split()) for _ in range(M)]
A, B = [list(i) for i in zip(*AB)]

reach = [[] for i in range(N+1)]
reach[0].append(1)

for i in range(M):
    reach[A[i]].append(B[i])
    reach[B[i]].append(A[i])

d = deque()
visited = [-1]*(N+1)
ans = [-1]*(N+1)

d.appendleft(1)
visited[1] = 0

while d:
    now = d.pop()
    nexts = reach[now]

    for next in nexts:
        if visited[next] == -1:
            visited[next] = visited[now] + 1
            ans[next] = now
            d.appendleft(next)
        elif visited[now]+1 < visited[next]:
            visited[next] = visited[now]
            ans[next] = now

print('Yes')
for v in ans[2:]:
    print(v)

Solution (Python):

import queue

n, m = list(map(int, input().split()))
edges = [list(map(int, input().split())) for _ in range(m)]


edges_dict = {}
for edge in edges:
    a, b = edge

    if a not in edges_dict:
        edges_dict[a] = [b]
    else:
        edges_dict[a].append(b)

    if b not in edges_dict:
        edges_dict[b] = [a]
    else:
        edges_dict[b].append(a)


prev_list = [None] * (n + 1)
q = queue.Queue()


q.put(1)
prev_list[1] = 1

while not q.empty():
    v = q.get()
    for w in edges_dict[v]:
        if prev_list[w] is None:
            prev_list[w] = v
            q.put(w)

print("Yes")
for v in prev_list[2:]:
    print(v)

Solution (Python):
from heapq import heappop, heappush
n,m = map(int,input().split())
G = [[] for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)
dist = [float("inf")]*n
seen = [False]*n
ans = [0]*n
def f(s):
    PQ = [(0,s)]
    dist[s] = 0
    while PQ:
        md,u = heappop(PQ)
        seen[u] = True
        if dist[u] < md: continue
        for v in G[u]:
            if seen[v]: continue
            if dist[v] > md+1:
                dist[v] = md+1
                heappush(PQ,(dist[v],v))
                ans[v] = u+1
f(0)
print("Yes")
for i in range(1,n): print(ans[i])

Solution (Python):
from collections import deque

class Node:
    def __init__(self, data):
        self.data = data
        self.children = []

def main():
    N, M = map(int, input().split())
    dic = {}
    for i in range(1, N + 1):
        dic[i] = Node(i)
    for i in range(0, M):
        A, B = map(int, input().split())
        dic[A].children.append(dic[B])
        dic[B].children.append(dic[A])

    answerDic = {}
    q = deque()
    q.append(dic[1])
    while len(q) > 0:
        current = q.popleft()
        for child in current.children:
            if child.data not in answerDic.keys() :
                answerDic[child.data] = current.data
                q.append(child)

    print('Yes')
    for key in range(2, N + 1):
        print(answerDic[key])

if __name__ == "__main__":
    main()

Solution (Python):
from queue import Queue

class Node:
    def __init__(self, data):
        self.data = data
        self.children = []

def main():
    N, M = map(int, input().split())
    dic = {}
    for i in range(1, N + 1):
        dic[i] = Node(i)
    for i in range(0, M):
        A, B = map(int, input().split())
        dic[A].children.append(dic[B])
        dic[B].children.append(dic[A])

    answerDic = {}
    q = Queue()
    q.put(dic[1])
    while not q.empty():
        current = q.get()
        for child in current.children:
            if child.data not in answerDic.keys() :
                answerDic[child.data] = current.data
                q.put(child)

    print('Yes')
    for key in range(2, N + 1):
        print(answerDic[key])

if __name__ == "__main__":
    main()

Solution (Python):
def main():
    import sys
    input = sys.stdin.buffer.readline
    n,m = map(int, input().split())
    adj = [[] for i in range(n)]
    for i in range(m):
        a,b = map(lambda x: int(x)-1, input().split())
        adj[a].append(b)
        adj[b].append(a)
    
    que = [0]
    parent = [-1] * (n)
    while que:
        node = que.pop(0)
        for child in adj[node]:
            if parent[node] == child:
                continue
            if parent[child] == -1:
                que.append(child)
                parent[child] = node
    if -1 in parent[1:]:
        print('No')
    else:
        print('Yes')
    for i in range(1,n):
        print(parent[i]+1)





if __name__ == '__main__':
    main()

Solution (Python):
N, M = map(int, input().split())
link = [[] for i in range(N)]
for i in range(M):
    A, B = map(int, input().split())
    link[A-1].append(B-1)
    link[B-1].append(A-1)
visited = [False for i in range(N)]
result = [0] * N
Q = [0]
visited[0] = True

while Q:
    
    v = Q.pop(0)
    for i in link[v]:
        if visited[i] == False:
            visited[i] = True
            result[i] = v
            Q.append(i)
print("Yes")
for i in range(1, N):
    print(result[i] + 1)

Solution (Python):
def resolve():
    def Dijkstra(s, n, edge, inf=float("inf")):
        import heapq
        d = [inf] * n
        used = [False] * n
        d[s] = 0
        used[s] = True
        queue = []
        path = [-9999] * n
        for e in edge[s]:
            heapq.heappush(queue, e + [s])
        while len(queue):
            dist, point, before = heapq.heappop(queue)
            if used[point]:
                continue
            d[point] = dist
            used[point] = True
            path[point] = before
            for nextdist, nextp in edge[point]:
                if not used[nextp]:
                    heapq.heappush(queue, [dist + nextdist, nextp, point])
        return d, path
    n, m = map(int, input().split())
    inf = 10 ** 10
    from collections import defaultdict
    edge = defaultdict(list)
    for _ in range(m):
        x, y = [int(x) - 1 for x in input().split()]
        edge[x].append([1, y])
        edge[y].append([1, x])
    l, p = Dijkstra(0, n, edge, inf)
    if min(p[1:]) < -1:
        print("No")
    else:
        print("Yes")
        for i in p[1:]:
            print(i + 1)


if __name__ == '__main__':
    resolve()

Solution (Python):
n,m=map(int,input().split())
r=[[] for x in range(n)]
for c in range(m):
    a,b=map(int,input().split())
    r[a-1].append(b-1)
    r[b-1].append(a-1)
s=[-1]*n
u=[0]
v=[]
k=1
for c in range(10**5):
    for d in u:
        for e in r[d]:
            if s[e]==-1:
                s[e]=d
                k+=1
                v.append(e)
    if k>n-1:
        break
    u=v
print('Yes')
for c in range(n-1):
    print(s[c+1]+1)

Solution (Python):
N, M = map(int, input().split())
X = [[] for i in range(N + 1)]
for i in range(M):
  a, b = map(int, input().split())
  X[a] += [b]
  X[b] += [a]
ans = [0] * (N + 1)
ans[1] = 1
from collections import deque
que = deque([1])
while que:
  q = que.popleft()
  for i in X[q]:
    if ans[i] == 0:
      ans[i] = q
      que.append(i)
print('Yes')
print(*ans[2:], sep='\n')

Solution (Python):
import queue
INF = float('inf')

def bfs():
    q = queue.Queue()
    [q.put([x, 0]) for x in graph[0]]
    while not q.empty():
        n = q.get()
        nex = n[0]; now = n[1]
        if visited[nex] == INF:
            visited[nex] = now
            [q.put([x, nex]) for x in graph[nex]]
    return

N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(M):
    A, B = map(int, input().split())
    graph[A-1].append(B-1)
    graph[B-1].append(A-1)

visited = [INF for _ in range(N)]
bfs()

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

Solution (Python):
from collections import deque

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

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

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

q = deque()

dist = [-1] * n
ans = [0] * n
q.append(0)

while len(q) != 0:
    now = q.popleft()
    for to in adj[now]:
        if dist[to] != -1: continue
        dist[to] = dist[now] + 1
        ans[to] = now
        q.append(to)

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

Solution (Python):
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)
    g[b-1].append(a)

from collections import deque

def bfs(u):
    queue = deque([u])
    d = [None] * n 
    d[u-1] = 0 
    while queue:
        v = queue.popleft()
        for i in g[v-1]:
            if d[i-1] is None:
                d[i-1] = d[v-1] + 1
                queue.append(i)
    return d

d = bfs(1)
for i in range(n):
    if d[i] == 0:
        print('Yes')
    else:
        for j in g[i]:
            if d[i]-1==d[j-1]:
                print(j)
                break

Solution (Python):
from collections import deque


N,M=map(int,input().split())
a=[]
min=[0] * (N + 1)
heya=[[] for _ in range(N + 1)]


for i in range(M):
    tmp = list(input().split())
    tmp_i = [int(s) for s in tmp]
    a.append(tmp_i)

heya[0].append(1)
for i in range(M):
    tmp1 = a[i][0]
    tmp2 = a[i][1]
    heya[tmp1].append(tmp2)
    heya[tmp2].append(tmp1)

que = list(heya[0])
prev = []
tmp = []
prevtmp =[]
cnt = 0
prev.append(0)
while cnt < 1000000:
    
    tmp.clear()
    prevtmp.clear()
    if len(que) == 0:
        
        break

    for i in range(len(que)):
        chk = que[i]
        
        

        
        if min[chk] == 0:
            
            
            min[chk] = prev[i]
            for j in range(len(heya[chk])):
                
                tmp.append(heya[chk][j])
                prevtmp.append(chk)

    
    que.clear()
    for i in range(len(tmp)):
        que.append(tmp[i])

    prev.clear()
    for i in range(len(prevtmp)):
        prev.append(prevtmp[i])

    cnt = cnt + 1


chk = 0
for i in range(1,N+1):
    if min[i] == 0:
        print('No')
        chk = 1
        break

if chk == 0:
    print('Yes')
    for i in range(2,N+1):
        print(min[i])

Solution (Python):
N, M = map(int, input().split())
A = [0]*M
B = [0]*M
for i in range(M):
    A[i], B[i] = map(int, input().split())

from collections import deque
def bfs(graph, start_node, depth):
    next_nodes = deque([])
    seen_nodes = set()
    
    next_nodes.append(start_node)
    seen_nodes.add(start_node)
    depth[start_node] = 0
    while next_nodes:
        node = next_nodes.popleft()


        if node in graph:
            for n in graph[node]:
                if not n in seen_nodes:
                    next_nodes.append(n)
                    seen_nodes.add(n)
                    depth[n] = node
    return

def Main(N, M, A, B):
    g = {}
    for i in range(M):
        if A[i] not in g:
            g[A[i]] = []
        if B[i] not in g:
            g[B[i]] = []
        g[A[i]].append(B[i])
        g[B[i]].append(A[i])
    depth = {}
    bfs(g, 1, depth)
    ans = []
    for i in range(2, N+1):
        ans.append(depth[i])
    return 'Yes', ans
          
                    
yn, out = Main(N, M, A, B)
print(yn)
for e in out:
    print(e)

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

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

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

INF = 10 ** 6

def dijkstra_travel(edges):
    dists = [ INF  for _ in range(n) ]
    paths = [ None for _ in range(n) ]

    dists[0] = 0
    paths[0] = 0

    next_travel = [ 0 ]

    def travel_adjacent():
        n = next_travel.pop(0)

        adjacent_nodes = list(
            map(
                lambda node: (node, paths[node]),
                edges[n],
            )
        )

        for node, path in adjacent_nodes:
            if path is None or dists[node] > dists[n] + 1:
                dists[node] = dists[n] + 1
                paths[node] = n
                next_travel.append(node)


    while len(next_travel) > 0:
        travel_adjacent()

    return paths[1:]

result = dijkstra_travel(edges)

if all(map(lambda x: x is not None, result)):
    print('Yes')

    for x in result:
        print(x + 1)

else:
    print('No')

Solution (Python):


from collections import defaultdict
import queue


q = queue.Queue()

n, m = map(int, input().split())
graph = defaultdict(list)
for _ in range(m):
    a, b = map(lambda x: int(x), input().split())
    graph[a].append(b)
    graph[b].append(a)




li = [-1 for _ in range(n)]
li[0] = 1

def search(x):



    




    for e in graph[x]:

        if li[e-1] != -1:
            continue
        li[e-1] = x

        q.put(e)
x = 1
search(x)
while q.queue:
    search(q.get())

if li[1:].count(-1) == 0:
    print('Yes')
    for e in li[1:]:
        print(e)
else:
    print('No')

Solution (Python):
import collections
def main():
    N,M = map(int, input().split())
    A = [0]*M
    B = [0]*M
    road = [[] for i in range(N)]
    for i in range(M):
        A[i],B[i] = map(lambda x:x-1, map(int, input().split()))
        road[A[i]].append(B[i])
        road[B[i]].append(A[i])
    
    
    
    remainroom = [True for i in range(N)]
    sign = [-1]*N
    cur = [0]
    while len(cur)>0:
        
        new = []
        for i in cur:
            for j in road[i]:
                if remainroom[j]:
                    remainroom[j]=False
                    sign[j] = i
                    new.append(j)
        cur = new

    
    coll = collections.Counter(remainroom)
    if coll.get(True,0)>0:
        print("No")
    else:
        print("Yes")
        for i in range(1,N):
            print(sign[i]+1)

main()

Solution (Python):
import pdb

def bfs(graph, start, rooms):
    queue = []
    visited = [False]*rooms
    visited[start] = True
    marking = [0]*rooms
    queue.append(start)
    while queue:
        nodes = queue.pop(0)
        for node in graph[nodes]:
            if not visited[node]:
                visited[node] = True
                queue.append(node)
                marking[node] = nodes + 1
    return marking, visited

if __name__=="__main__":
    N, M = map(int, input().split())
    graph = [[] for i in range(N)]
    for i in range(M):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append(b)
        graph[b].append(a)

    marking, visited = bfs(graph, 0, N)

    if all(visited):
        print("Yes")
        for i in range(1, N):
            print(marking[i])
    else:
        print("No")

Solution (Python):
def resolve():
    def Dijkstra(s, n, edge, inf=float("inf")):
        import heapq
        d = [inf] * n
        used = [False] * n
        d[s] = 0
        used[s] = True
        queue = []
        path = [-9999] * n
        for e in edge[s]:
            heapq.heappush(queue, e + [s])
        while len(queue):
            dist, point, before = heapq.heappop(queue)
            if used[point]:
                continue
            d[point] = dist
            used[point] = True
            path[point] = before
            for nextdist, nextp in edge[point]:
                if not used[nextp]:
                    heapq.heappush(queue, [dist + nextdist, nextp, point])
        return d, path
    n, m = map(int, input().split())
    inf = 10 ** 10
    edge = [[] for _ in range(n)]
    for _ in range(m):
        x, y = [int(x) - 1 for x in input().split()]
        edge[x].append([1, y])
        edge[y].append([1, x])
    l, p = Dijkstra(0, n, edge, inf)
    if min(p[1:]) < -1:
        print("No")
    else:
        print("Yes")
        for i in p[1:]:
            print(i + 1)


if __name__ == '__main__':
    resolve()

Solution (Python):

import sys
from collections import deque


input = sys.stdin.readline
def IS(cb): return cb(input().strip())
def IL(cb): return [cb(s) for s in input().strip().split()]
def IR(cb, rows): return [IS(cb) for _ in range(rows)]
def ILL(cb, rows): return [IL(cb) for _ in range(rows)]


def solve():
    N, M = IL(int)
    AB = ILL(int, M)
    graph = [[] for _ in range(N)]
    for a, b in AB:
        graph[a - 1].append(b - 1)
        graph[b - 1].append(a - 1)
    que = deque()
    que.append(0)
    visited = [False] * N
    visited[0] = True
    route = [0] * N
    while len(que):
        current = que.popleft()
        for next in graph[current]:
            if not visited[next]:
                visited[next] = True
                que.append(next)
                route[next] = current + 1

    print('Yes')
    for i in route[1:]:
        print(i)


solve()

Solution (Python):
N, M = map(int, input().split())
link = [[] for i in range(N)]
for i in range(M):
    A, B = map(int, input().split())
    link[A-1].append(B-1)
    link[B-1].append(A-1)
visited = [False for i in range(N)]
result = [0] * N
Q = [0]
visited[0] = True

while Q:
    
    v = Q.pop(0)
    for i in link[v]:
        if visited[i] == False:
            visited[i] = True
            result[i] = v
            Q.append(i)
print("Yes")
for i in range(1, N):
    print(result[i] + 1)

Solution (Python):
import collections
n,m = list(map(int,input().split()))

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

ans=[-1]*n
ans[0]=0
que = [0]


while que:
    v = que.pop(0)
    for i in di[v]:
        if ans[i]!=-1:continue
        ans[i]=v
        que.append(i)
    

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

Solution (Python):
from collections import deque
n, m = map(int, input().split())
l = [[] for i 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)
que = deque([0])
visited = [False] * n
visited[0] = True
prev = [0] * n
while que:
    p = que.popleft()
    for i in l[p]:
        if visited[i]:
            continue
        visited[i] = True
        prev[i] = p
        que.append(i)
print("Yes")
for i in prev[1:]:
    print(i + 1)

Solution (Python):
from heapq import heappush, heappop

INF = 10**15

def dijkstra(s, edges):
    n = len(edges)
    que = []
    d = [INF] * n
    prev = [-1] * n
    d[s] = 0
    heappush(que, (0, s))

    while len(que) > 0:
        (c, v) = heappop(que)
        if d[v] < c:
            continue
        for (cc, w) in edges[v]:
            if d[w] > d[v] + cc:
                d[w] = d[v] + cc
                prev[w] = v
                heappush(que, (d[w], w))

    return d, prev

n, m = map(int, input().split())
edges = [[] for i in range(n)]
for i in range(m):
    ui, vi = map(int, input().split())
    ui, vi = vi-1, ui-1
    edges[ui].append((1, vi))
    edges[vi].append((1, ui))

d, prev = dijkstra(0, edges)
print('Yes')
for i in range(1, n):
    print(prev[i]+1)