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: Wrong Answer

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

def dijkstra(s,n,w,cost):
    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,used

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

ans,used= dijkstra(0,n,m,cost)

if(False in used):print("No")
else:
    print("Yes")
    for i in ans:
        print(i)

Submission status: Wrong Answer

Solution code:
def check(go):
    for i in range(1, len(go)):
        if (go[i] == -1):
            return True

    return False


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

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

    G[A-1][B-1] = 1
    G[B-1][A-1] = 1

go = [-1] * N
flag = [False] * N


while (check(go)):
    #    print("===")
    for i in range(N):
        if (flag[i] == True):
            continue
        else:
            #            print("-", i, "-")
            flag[i] = True

            for j in range(1, N):
                if (G[i][j] == 1):
                    go[j] = i
#                    print(j, "=>", i)
            print(go)

        if (check(go) == False):
            print("Yes")
            for i in range(1, len(go)):
                print(go[i] + 1)
            exit(0)

"""
for i in range(1, len(go)):
    print(go[i]+1)
"""

Submission status: Wrong Answer

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)]
cost=[2<<32]*n
seen=[False]*n

def dfs(G,v,depth):
    seen[v]=True
    cost[v]=min(cost[v],depth)
    for i in G[v]:
        if seen[i]:
            continue
        dfs(G,i,depth+1)
    seen[v]=False


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

dfs(graph,0,0)
cost[0]=0
if max(cost)==2<<32:
    print("No")
else:
    print("Yes")
    for i in range(1,n):
        print(cost[i])

Submission status: Wrong Answer

Solution code:
from sys import stdin
from collections import deque,defaultdict

N, M = [int(x) for x in stdin.readline().rstrip().split()]

par = [i for i in range(N+1)]
rank = [0] * (N+1)
size = [1] * (N+1)


def find(x):
    if par[x] == x:
        return par[x]
    else:
        par[x] = find(par[x])
        return par[x]


def union(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    if rank[x] < rank[y]:
        par[x] = y
        size[y] += size[x]
        size[x] = 0

    else:
        par[y] = x
        size[x] += size[y]
        size[y] = 0
        if rank[x] == rank[y]:
            rank[x] += 1


def check_same(x, y):
    return find(x) == find(y)


def check_size(x):
    return size[find(x)]



from collections import defaultdict
adj = defaultdict(set)

for _ in range(M):
    A, B = [int(x) for x in stdin.readline().rstrip().split()]
    union(A, B)
    adj[A].add(B)
    adj[B].add(A)
 
if len(set(par[1:])) == 1:
    print("Yes")
    ans = [0]*(N+1)
    visit_p = deque()
    visit_p.append((1,0))
    visited = [False]*(N+1)
    visited[1] = True
    
    while visit_p:
        now_v,dist = visit_p.popleft()
        for v in adj[now_v]:
            if visited[v]:
                continue
            ans[v] = now_v
            visited[v] = True
            visit_p.append((v,1+dist))

    for k in ans[2:]:
      print(k)
else:
    print("No")

Submission status: Wrong Answer

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

def search(i):
    d = dist[i]
    for p in path[i]:
        if dist[p] > d 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())
    path[a].append(b)
    path[b].append(a)
    if a == -1:
        mark[b] = -1
        dist[b] = 1
        search(b)
    elif b == -1:
        mark[a] = -1
        dist[a] = 1
        search(a)
    elif mark[a] != -2:
        if mark[b] != -2:
            if dist[a] > dist[b]:
                mark[a] = b
                dist[a] = dist[b] + 1
                search(a)
            elif dist[a] < dist[b]:
                mark[b] = a
                dist[b] = dist[a] + 1
                search(b)
        else:
            dist[b] = dist[a] + 1
            mark[b] = a
            search(b)
    elif mark[b] != -2:
        mark[a] = b
        dist[a] = dist[b] + 1
        search(a)
if mark.count(-2) > 0:
    print("No")
else:
    print("Yes")
    for i in mark: print(i+2)

Submission status: Wrong Answer

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

arr = []

for i in range(M):
  List = list(map(int,input().split()))
  List.sort()
  arr.append(List)
arr.sort()  

ans = []
c = [-1 for i in range(N+1)]
for i in range(M):
  
  a = arr[i][0]
  b = arr[i][1]
  
  if a == 1:
    c[b] = 1
  if c[a] != -1 and c[b] == -1:
    c[b] = a
  elif c[b] != -1 and c[a] == -1:
    c[a] = b
    
c[0] = 1
ck = 0
for i in range(N+1):
  if c[i] == -1:
    ck = 1
if ck == 1:
  print("No")
else:
  print("Yes")
  for i in range(2,N+1):
    print(c[i])

Submission status: Wrong Answer

Solution code:
# import sys
# readline = sys.stdin.readline
# generator = (readline().strip() for _ in range(N))

# import numpy as np
# from itertools import permutations
# from itertools import combinations
# from itertools import combinations_with_replacement
import queue
# import heapq

# N, M = map(int, input().split())
# As = list(map(int, input().split()))
# queries = (input() for _ in range(N))


def solve():
    N, M = map(int, input().split())
    queries = (map(int, input().split()) for _ in range(M))

    tree = [set() for _ in range(N+1)]

    for a, b in queries:
        tree[a].add(b)
        tree[b].add(a)

    nn = 10 ** 9
    signs = [nn for _ in range(N+1)]
    visited = {0}

    que = queue.Queue()

    que.put((1, 0))  # parent, current, distance

    while not que.empty():

        current, d = que.get()

        if current in visited:
            continue

        visited.add(current)

        d = min(d, signs[current])
        signs[current] = d

        for t in tree[current]:
            if t in visited:
                continue
            else:
                que.put((t, d+1))

    return signs[2:]


def main():
    ans = solve()
    print('Yes')
    for a in ans:
        print(a)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def get_target_min_index(min_index, distance, unsearched_nodes):
    start = 0
    while True:
        index = distance.index(min_index, start)
        found = index in unsearched_nodes
        if found:
            return index
        else:
            start = index + 1


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

route_list = [[0 for i in range(N)] for j in range(N)]

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

unsearched_nodes = list(range(N))
distance = [float('inf') for i in range(N)]
distance[0] = 0
previous_nodes = [-1] * N

while(len(unsearched_nodes) != 0): #未探索ノードがなくなるまで繰り返す
    # まず未探索ノードのうちdistanceが最小のものを選択する
    posible_min_distance = float('inf') # 最小のdistanceを見つけるための一時的なdistance。初期値は inf に設定。
    for node_index in unsearched_nodes: # 未探索のノードのループ
        if posible_min_distance > distance[node_index]: 
            posible_min_distance = distance[node_index] # より小さい値が見つかれば更新
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes) # 未探索ノードのうちで最小のindex番号を取得
    unsearched_nodes.remove(target_min_index) # ここで探索するので未探索リストから除去

    target_edge = route_list[target_min_index] # ターゲットになるノードからのびるエッジのリスト
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis # 過去に設定されたdistanceよりも小さい場合はdistanceを更新
                previous_nodes[index] =  target_min_index #　ひとつ前に到達するノードのリストも更新

ans = 0
for i in range(1,N):
    if previous_nodes[i] == -1:
        ans = 1

if ans == 0:  
    for i in range(N):
        if i == 0:
            print('yes')
        else:
            print(previous_nodes[i]+1)
else:
    print("no")

Submission status: Wrong Answer

Solution code:
N, M = map(int,input().split())
A = []
B = []
for i in range(M):
  a, b = map(int,input().split())
  A.append(a)
  B.append(b)
  
link_dic = {}
for i in range(M):
  if A[i] not in link_dic.keys():
  	link_dic[A[i]] = [B[i]]
  else:
  	link_dic[A[i]].append(B[i])
  if B[i] not in link_dic.keys():
  	link_dic[B[i]] = [A[i]]
  else:
  	link_dic[B[i]].append(A[i])

sign = [0] * N
j = 1
current_room = [1]

def search_room(l):
  global current_room
  did = 0
  next_cr = []
  for i in l:
    li = link_dic[i]
    for k in range(len(li)):
      if sign[li[k]-1] == 0:
        sign[li[k]-1] = i
        next_cr.append(li[k])
        did += 1
        
  current_room = list(next_cr)
        
  if did == 0:
  	return 1
  else:
  	return 0
  	
while j > 0:
  result = search_room(current_room)
  if result:
  	break

sign_ans = sign[1:N]
for i in sign_ans:
  print(i)

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

Solution code:
from collections import deque

n,m=map(int,input().split())
L=[[] for i in range(n)]

#print(L)

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

#print(L)
d=[float('inf') for i in range(n)]
m=[0 for i in range(n)]

def bfs():

    que=deque([])
    que.append(0)
    d[0]=0
    
    while que:
        p=que.popleft()
        for np in L[p]:
            if d[np]==float('inf'):
                que.append(np)
                d[np]=d[p]+1
                m[np]=p+1

bfs()
if sum(d)==float('inf'):
    print('No')
else:
    for i in range(1,n):
        print(m[i])

Submission status: Wrong Answer

Solution code:
#import re
import sys
input = sys.stdin.readline
#import heapq
#import bisect
from collections import deque
#import math

def main():
    n, m = map(int, input().split())
    AL = [[] for i in range(n+1)]
    check = [0 for i in range(n+1)]
    for i in range(m):
        s, e = map(int, input().split())
        AL[s].append(e)
        AL[e].append(s)
    que = deque()
    pb = 1, 1
    que.append(pb)
    ANS = [0 for i in range(n+1)]
    while(que):
        pb = que.popleft()
        p = pb[0]
        b = pb[1]
        if check[p] == 1:
            continue
        elif check[p] == 0:
            ANS[p] = b
            check[p] = 1
            for num in AL[p]:
                que.append((num, p))
    print("yes")
    for i in range(n+1):
        if i in [0, 1]:
            continue
        else:
            print(ANS[i])

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import heapq
def dijkstra_heap(s, n, edge):
    d = [float("inf")] * n
    used = [True] * n
    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, M = map(int, input().split())

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

distance = dijkstra_heap(0, N, edge)

for d in distance:
    if d == float("inf"):
        print("No")
        exit()

print("Yes")
for i in range(1, N):
    print(distance[i])

Submission status: Wrong Answer

Solution code:
import sys
import  math
from heapq import *
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

    
N,M=nm()
INF=10**18
def bfs(start,edge):
    d=[INF]*(N+1)
    ans=[0]*(N+1)
    d[start]=0
    q=[(0,start)]
    while(len(q)!=0):
        ci,i=heappop(q)
        for j in edge[i]:
            if(d[j]>=d[i]+1):
                d[j]=d[i]+1
                heappush(q,(d[j],j))
                ans[j]=i

    return ans




edge=[[]for _ in range(N+1)]
for i in range(M):
    A,B=nm()
    edge[A].append(B)
    edge[B].append(A)

ans=bfs(1,edge)

print(ans)
for i in range(2,N+1):
    if(ans[i]==0):
        print('No')
        sys.exit(0)

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

Submission status: Wrong Answer

Solution code:
N,M=list(map(int,input().split()))
AB=[[]]*M
distance=[0]*(N+1)
distance[0]=-1
for i in range(0,M):
    AB[i]=list(map(int,input().split()))

for i in range(1,N):
    for j in range(0,M):
        if AB[j][0]==i and distance[AB[j][1]]==0:
            distance[AB[j][1]]=i
        elif AB[j][1]==i and distance[AB[j][0]]==0:
            distance[AB[j][0]]=i
    if distance.count(0)==0:
        break
print('yes')
for i in range(1,N):
    print(distance[i])

Submission status: Wrong Answer

Solution code:
import heapq

n, m = map(int, input().split())
to = {}
for i in range(m):
    a, b = map(int, input().split())
    from_a = to.get(a, set())
    from_a.add(b)
    to[a] = from_a
    from_b = to.get(b, set())
    from_b.add(a)
    to[b] = from_b
ans = [0] * (n + 1)
ans[1] = 1
nx = []
heapq.heapify(nx)
heapq.heappush(nx, 1)
while len(nx) != 0:
    cur = heapq.heappop(nx)
    nxts = to.get(cur, [])
    for nxt in nxts:
        if ans[nxt] != 0:
            continue
        ans[nxt] = cur
        heapq.heappush(nx, nxt)
if 0 in ans[2:]:
    print('No')
    exit()
else:
    print('Yes')
    [print(i) for i in ans[2:]]

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)

N, M = map(int, input().split())
g = [[int(i) for i in input().split()] for j in range(M)]

G = [[] for i in range(N)]
for i in range(M):
    a, b = g[i]
    G[a-1].append(b-1)
    G[b-1].append(a-1)

def dfs(v, pre):
    b = False
    for next_v in G[v]:
        if marks[next_v] == -1:
            marks[next_v] = v
            b = True
    if b:
        for next_v in G[v]:
                dfs(next_v, v)
            
marks = [-1 for i in range(N)]
dfs(0, 0)
if -1 not in marks:
    print("Yes")
    for i in range(1, N):
        print(marks[i]+1)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque as de
import math
import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix


def num():
    return int(input())


def nums():
    return map(int,input().split())

n,m = nums()

root = [list(nums()) for _ in range(m)]

res = [[math.inf]*n  for _ in range(n)]

for i in range(n):
    res[i][i] = 0

for i,j in root:
     
    res[i-1][j-1] = res[j-1][i-1] = 1

res = csr_matrix(res)
res = dijkstra(res)

if math.inf in res:
    print('No')
else:
    print('Yes')
    for i in res[0][1:]:
        print(int(i))

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

import heapq


def Bellman_Ford(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [Max] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    po = 0
    while po < 2*N + 100:
        update = False
        for p,q,r in es:
        # e: 辺iについて [from,to,cost]
            if d[p] != Max and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
        if not update:
            break
        po += 1
    return d


def dijkstra():
    #n:ノード数e:辺数,w:スタート

    edge = [[] for i in range(n)]
    dg = 10**7
    # edge[i]:[コスト]
    for i in range(e):
        x,y = map(int,input().split())
        z = 1
        x -= 1
        y -= 1
        edge[x].append(z*dg + y)
        edge[y].append(z*dg + x)
    
    s = w-1
    d = [-1]*n
    d[s] = 0

    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)

        

    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v,c = minedge%dg,minedge//dg
        if d[v] >= 0:
            continue
        d[v] = c
        for e in edge[v]:
            vNext = e%dg
            if d[vNext]:
                heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)

    return d


def warshall_floyd(n,d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d






N,M = m()


n = N
w = 1
gr = [[] for i in range(n)]
edge = [[] for i in range(n)]
dg = 10**7
# edge[i]:[コスト]
for i in range(M):
    a,b = map(int,input().split())
    z = 1
    a -= 1
    b -= 1
    gr[a].append(b)
    gr[b].append(a)
    edge[a].append(z*dg + b)
    edge[b].append(z*dg + a)

s = w-1
d = [-1]*n
d[s] = 0

edgelist = []
for e in edge[s]:
    heapq.heappush(edgelist,e)

    

while len(edgelist):
    minedge = heapq.heappop(edgelist)
    v,c = minedge%dg,minedge//dg
    if d[v] >= 0:
        continue
    d[v] = c
    for e in edge[v]:
        vNext = e%dg
        if d[vNext]:
            heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)
print("Yes")
for i in range(1,N):
    for j in gr[i]:
        if d[i] == d[j]+1:
            print(j+1)

Submission status: Wrong Answer

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

ans = [-1] * (N+1)
graph = [[] for _ in range(N+1)]
for a,b in AB:
    graph[a].append(b)
    graph[b].append(a)

for i in range(N+1):
    graph[i].sort()
    
from collections import deque
todo = deque([(1,0)])
while todo:
    x,parent = todo.pop()
    ans[x] = parent
    for y in graph[x]:
        if y == parent:
            continue
        if ans[y] == -1:
            todo.append((y,x))
print('Yes')
for i in range(2,N+1):
    print(ans[i])

Submission status: Wrong Answer

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**6
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: Wrong Answer

Solution code:
n,m=map(int,input().split())
marks = {i+1:-1 for i in range(n)}
roots = {i+1:[] for i in range(n)}
count = 0
for i in range(m):
    a,b = map(int,input().split())
    roots[a].append(b)
    roots[b].append(a)

before_room = 1
searchs = [{'root':roots[1], 'mark':1}]
while searchs != []:
    next_search = []
    for search in searchs:
        for root in search['root']:
            new_root = []
            if marks[root] == -1:
                marks[root] = search['mark']
                count += 1
                new_root += roots[root]
            else:
                continue
            next_search.append({'root':roots[root], 'mark':root})
    if count >= n-1:
        break
    searchs = next_search[:]

del marks[1]
print('Yes')
for v in marks.values():
    print(v)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import collections

sys.setrecursionlimit(10 ** 7)

# 1 ✕ N
N, M = list(map(int, input().rstrip().split()))

# N ✕ M
A = list(tuple(map(int, input().rstrip().split())) for _ in range(M))

array = [[] for _ in range(N)]
for x, y in A:
    array[x - 1].append(y - 1)
    array[y - 1].append(x - 1)

result = []
for i in range(1, N):
    ans = 0
    visit = [-1] * N
    visit[i] = ans

    queue = []
    for t in array[i]:
        queue.append(t)

    found = False
    while True:
        # print(queue)
        tmp = []
        ans += 1
        for q in queue:
            if visit[q] != -1:
                continue

            if q == 0:
                result.append(ans)
                tmp = []
                found = True
                break

            visit[q] = ans
            for t in array[q]:
                tmp.append(t)

        if len(tmp) == 0:
            break
        else:
            for t in tmp:
                queue.append(t)

    if not found:
        print("No")
        sys.exit()

print("Yes")
for i in result:
    print(i)

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
D = [list(map(int,input().split())) for _ in range(M)]
D.sort(key=lambda x:x[0])
D
ls = [[N,0] for _ in range(N)]
ls[0][0] = 0

for e in D:
    if ls[e[0]-1][0]+1 < ls[e[1]-1][0]:
        ls[e[1]-1][0] = ls[e[0]-1][0]+1
        ls[e[1]-1][1] = e[0]

    if ls[e[0]-1][0] > ls[e[1]-1][0]+1:
        ls[e[0]-1][0] = ls[e[1]-1][0]+1
        ls[e[0]-1][1] = e[1]

ls.pop(0)


if [N,0] not in ls:
    print('Yes')
    for n,ans in ls:
        print(ans)

else:
    print('No')

Submission status: Wrong Answer

Solution code:
#import re
import sys
input = sys.stdin.readline
#import heapq
#import bisect
from collections import deque
#import math

def main():
    n, m = map(int, input().split())
    AL = [[] for i in range(n+1)]
    check = [0 for i in range(n+1)]
    for i in range(m):
        s, e = map(int, input().split())
        AL[s].append(e)
        AL[e].append(s)
    que = deque()
    pb = 1, 1
    que.append(pb)
    ANS = [0 for i in range(n+1)]
    while(que):
        pb = que.popleft()
        p = pb[0]
        b = pb[1]
        if check[p] == 1:
            continue
        elif check[p] == 0:
            ANS[p] = b
            check[p] = 1
            for num in AL[p]:
                que.append((num, p))
    print("yes")
    for i in range(n+1):
        if i in [0, 1]:
            continue
        else:
            print(ANS[i])
                
    

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

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

route = deque([ [0]*n for i in range(n)])

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

mi = deque([n] * n)
mi[0] = 0
check = deque([n] * n)

for i in range(len(route)):
    for j in range(len(route[i])):

        if route[i][j] == 1:
            if mi[j] > mi[i] + 1:
                mi[j] = mi[i] + 1
                check[j] = i

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

Submission status: Wrong Answer

Solution code:
from collections import deque

[N, M] = [ int(x) for x in input().split() ]

G = dict()
for i in range(1,N+1):
    G[i] = set()

for i in range(M):
    [A,B] = [ int(x) for x in input().split() ]
    G[A].add(B)
    G[B].add(A)

ans = [0]*(N+1)

Q = deque([1])
visited = set()
while Q:
    room = Q.popleft()
    
    if room not in visited:
        visited.add(room)
        
        for r in G[room]:
            if r not in visited:
                ans[r] = room
                Q.append(r)
ans[1] = 'Yes'
for i in range(1, N+1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
def check(go):
    for i in range(1, len(go)):
        if (go[i] == -1):
            return True

    return False


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

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

    G[A-1][B-1] = 1
    G[B-1][A-1] = 1

go = [-1] * N
flag = [False] * N


while (check(go)):
    print("===")
    for i in range(N):
        if (flag[i] == True):
            continue
        else:
            print("-", i, "-")
            flag[i] = True

            for j in range(1, N):
                if (G[i][j] == 1):
                    go[j] = i
                    print(j, "=>", i)
            print(go)

        if (check(go) == False):
            print("Yes")
            for i in range(1, len(go)):
                print(go[i] + 1)
            exit(0)

Submission status: Wrong Answer

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)
for ans in reachable_room_map.values():
    print(ans)

Submission status: Wrong Answer

Solution code:
import collections

def get_input():
    return list(map(lambda x:int(x), input().split()))

def main():
    inp = get_input()
    n, m = inp[0], inp[1]
    adj_list = [[] for i in range(n)]
    for i in range(m):
        inpu = get_input()
        a, b = inpu[0], inpu[1]
        adj_list[a - 1].append(b - 1)
        adj_list[b - 1].append(a - 1)
    
    q = collections.deque()
    visited = set()
    q.append(0)
    visited.add(0)
    p = [-1] * n

    #print(adj_list)
    while q:
        u = q.popleft()
        for i in adj_list[u]:
            #print("checking", u, i)
            if i not in visited:
                q.append(i)
                visited.add(i)
                p[i] = u
    #print(p)
    
    for i in range(1, len(p)):
        if p[i] == -1:
            print("NO")
            return

    print("YES")
    for i in range(1, n):
        print(p[i] + 1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m = map(int,input().split())

path = []
net = [[] for _ in range(n+1)]
for _ in range(m):
    a,b = map(int,input().split())

    net[a].append(b)
    net[b].append(a)

a = [-1] * (n+1)
d = deque()
d.append(1)
while d:
    u = d.popleft()
    for child in net[u]:
        if a[child] != -1:continue
        a[child] = u
        d.append(child)
a = a[1:]
for z in a:
    if z == -1:
        print("No")
        exit()
print("Yes")
for z in a:
    print(z)

Submission status: Wrong Answer

Solution code:
n,m = map(int, input().split())
link = [list(map(int, input().split())) for _ in range(m)]

import numpy as np
stack = [[] for j in range(n)]
value = np.ones(n) * 1000000
ans = np.zeros(n)
# print(stack)
for i in link:
    stack[i[0]-1].append(i[1]-1)
    stack[i[1]-1].append(i[0]-1)
# print(stack)
value[0] = 0
for i in range(n):
    for j in stack[i]:
        # print('ye',i,j)
        if value[j] > value[i]+1:
            ans[j] = i+1
        value[j] = min(value[j],value[i]+1)
        

# print(value)
print('Yes')
for i in ans[1:]:
    print(int(i))