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:
mod = 10**9+7
import sys
import math
from collections import Counter, defaultdict, deque
from itertools import product, permutations, combinations, combinations_with_replacement
from itertools import accumulate
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from math import ceil,floor
from copy import deepcopy
from heapq import heappop,heappush,heapify
import heapq


# def combinations(n, r):
# 	return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

# def gcd(a, b):
# 	if b == 0:
# 		return a
# 	else:
# 		return gcd(b, a%b)
 
# def lcm(a, b):
# 	return a // gcd(a, b) * b

# l = ['a', 'a', 'a', 'a', 'b', 'c', 'c']
# c = Counter(l)

# d = defaultdict(int)

sys.setrecursionlimit(10 ** 6)

int1 = lambda x: int(x) - 1

# リストの要素を改行を挟んで表示する
p2D = lambda x: print(*x, sep="\n")
# 入力を整数に変換して受け取る
def II(): return int(sys.stdin.readline())

def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())

# 入力全てを整数に変換したものの配列を受け取る
# def LI(): return list(map(int, sys.stdin.readline().split()))
# 入力全てを整数に変換して1引いたものの配列を受け取る
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LI(): return list(map(lambda x:int(x), sys.stdin.readline().split()))
def HI(): return list(map(lambda x:int(x)*(-1), sys.stdin.readline().split()))


N,M = MI()
A = []
B = []
for _ in range(M):
	a,b = MI()
	A.append(a)
	B.append(b)

d = defaultdict(int)
ref_list = [''] * N

for aa, bb in zip(A,B):
	ref_list[bb-1] += str(aa)
	ref_list[aa-1] += str(bb)


def rec(i, done, num):
	if d[str(i)]==0:
		d[str(i)] = num
	else:
		d[str(i)] = min(num, d[str(i)])
	candidate = list(set(ref_list[int(i)-1]))
	candidate = [c for c in candidate if not c in done]
	new_done = done+candidate
	for c in candidate:
		if not c in done:
			rec(c, new_done, num+1)
	return


rec(1, ['1'], 10)
ans = []
for i in range(1,N):
	d_i = d[str(i+1)]
	for target in list(set(ref_list[i])):
		if d[str(target)] == d_i -1:
			ans.append(target)
			break

if len(ans)==N-1:
	print('Yes')
	for f in ans:
		print(f)
else:
	print('No')

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(9999)

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

ps = [-1] * n
ps[0] = 0
tmps = {}
for _ in range(m):
    a,b=map(int,input().split())
    ai,bi=a-1,b-1
    if ai not in tmps:
        tmps[ai] = []
    tmps[ai].append(bi)
    if bi not in tmps:
        tmps[bi] = []
    tmps[bi].append(ai)

# print(tmps)

if 0 not in tmps:
    print("No")
    exit()


try:
    def puts(ks):
        nks = []
        for k in ks:
            _nks = tmps[k]
            for nk in _nks:
                if ps[nk] == -1:
                    ps[nk] = k
                    nks.append(nk)
            # print(k, ps)
        if nks == []:
            return
        # print(ks, ps)
        puts(nks)  
    ks = [0]
    puts(ks)

    # print(ps)

    if -1 in ps:
        print("No")
        exit()

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

except:
    print("No")

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
edge=[]
for _ in range(m):
    a,b=map(int,input().split())
    a-=1
    b-=1
    s=max(a,b)
    t=min(a,b)
    edge.append((t,s))
edge.sort()
#unionfind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n


    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]


    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)


        if x == y:
            return


        if self.parents[x] > self.parents[y]:
            x, y = y, x


        self.parents[x] += self.parents[y]
        self.parents[y] = x


    def size(self, x):
        return -self.parents[self.find(x)]


    def same(self, x, y):
        return self.find(x) == self.find(y)
uf = UnionFind(n)
ans=[-1]*n
edges=[[] for _ in range(n)]
for e in edge:
    s, t = e
    if not uf.same(s, t):
        uf.union(s, t)
        edges[s].append(t)
        edges[t].append(s)
#print(edges)
visited=[True]*n
stack=deque([0])
visited[0]=False
while stack:
    x=stack.pop()
    for nx in edges[x]:
        if visited[nx]:
            visited[nx]=False
            stack.append(nx)
            ans[nx]=x
for i in range(1,n):
    if visited[i]:
        print("No")
        exit()
print("Yes")
for i in ans[1:]:
    print(i+1)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    from collections import defaultdict,deque
    sys.setrecursionlimit(10**5+2)

    N,M=list(map(int,sys.stdin.readline().split()))
    dic=defaultdict(list)
    for i in range(M):
        A,B=list(map(int,sys.stdin.readline().split()))
        dic[A].append(B)
        dic[B].append(A)
    
    L=[-1]*(N+1)
    R=[-1]*(N+1)


    d = deque()
    d.append((1,1))
    while len(d):
        now,count=d.popleft()
        for goto in dic[now]:
            if L[goto]==-1 or count<L[goto]:
                L[goto]=count
                R[goto]=now
                d.append((goto,count+1))
        print(d)

    if any(x+1 for x in R[2:]):
        print('Yes')
        for x in R[2:]:
            print(x)
    else:
        print('No')
    


main()

Submission status: Wrong Answer

Solution code:
import sys

n, m = list(map(int, sys.stdin.readline().split()))
adj = [[] for _ in range(n+1)]
cnt = [0 for _ in range(n+1)]
arrived = [False for _ in range(n+1)]
segment = [0, 0]

def bfs(i):
    global visited
    
    queue = [i]
    visited[i] = True
    temp = 0
    segment[0] = 1
    arrived = False

    while queue != []:
        node = queue.pop(0)
        segment[0] -= 1
        
        if node == 1:
            arrived = True
            break
        
        for edge in adj[node]:
            if not visited[edge]:
                visited[edge] = True
                segment[1] += 1
                queue.append(edge)
                
        if segment[0] == 0:
            temp += 1
            segment[0], segment[1] = segment[1], 0
        
    return temp, arrived




for _ in range(m):
    u, v = list(map(int, sys.stdin.readline().split()))
    adj[u].append(v)
    adj[v].append(u)
    
for i in range(1,n+1):
    visited = [0 for _ in range(n+1)]
    cnt[i], arrived[i] = bfs(i)

if False in arrived[1:]:
    print('No')
else:
    print('Yes')
    for i in range(2,n+1):
        print(cnt[i])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	D
# CreatedDate:  2020-05-17 22:04:10 +0900
# LastModified: 2020-05-17 22:22:23 +0900
#

from collections import deque

def bfs(path_list,guide,n):
    color = [0]*(n+1)
    color[1] = 1
    Q = deque()
    Q.append(1)
    while Q:
        u = Q.popleft()
        for v in path_list[u]:
            if color[v] == 0:
                color[v]=1
                Q.append(v)
                guide[v]=u

def main():
    n,m = map(int,input().split())
    path_list = [[] for _ in range(n+1)]
    for _ in range(m):
        a,b = map(int,input().split())
#        print(a,b)
        path_list[a].append(b)
        path_list[b].append(a)

#    print(path_list)
    
    guide = [0]*(n+1)
    bfs(path_list,guide,n)
    print("Yes")
    for i in range(2,n):
        print(guide[i])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque



n,m = map(int,input().split())
ab = [[] for _ in range(m)]
kr = [[] for _ in range(n)]
dist = [-1 for _ in range(n)]
dist[0] = 0
ans = [-1 for _ in range(n)]
qn = deque([1])
for i in range(m):
    a,b = map(int,input().split())
    a,b = min(a,b),max(a,b)
    ab[i] = [a,b]
    kr[a-1].append(b)
    kr[b-1].append(a)

dis = 1
while len(qn) > 0:
    v = qn.popleft()
    d = dist[v-1]
    for w in kr[v-1]:
        if dist[w-1] > -1:
            continue
        dist[w-1] = d + 1
        qn.append(w)
        ans[w-1] = v


#print(dist)

#ab.sort()
#print(ab)
#print(kr)

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

Submission status: Wrong Answer

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

li = []
for i in range(M):
    li.append(list(map(int,input().split())))
ans = [0] * (N+1)
#print(ans)
que = [1]
#print(li)
def saiki ():
    global que
    global li
    global ans
    #print(que)
    q = que.pop(0)
    count = 0
    while True:
        
        if count == len(li):
            break
        #print(li)
        #print(count)
        if li[count][0] == q and ans[li[count][1]] == 0:
            que.append(li[count][1])
            ans[li[count][1]] = q
            li.pop(count)
        elif li[count][1] == q and ans[li[count][0]] == 0:
            que.append(li[count][0])
            ans[li[count][0]] = q
            li.pop(count)
        else:
            count += 1
    if len(que) == 0:
        for ai in ans:
            if ai != 0:
                print(ai)
    else:
        saiki()

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split(" "))
routes = {}
for i in range(M) :
    a,b = map(int, input().split(" "))
    if a not in routes :
        routes[a] = {}
        routes[a]["routeList"] = []
        routes[a]["cost"] = 99999999999999
        routes[a]["minRoute"] = 99999999999999
    if b not in routes :
        routes[b] = {}
        routes[b]["routeList"] = []
        routes[b]["cost"] = 99999999999999
        routes[b]["minRoute"] = 99999999999999
    
    routes[a]["routeList"].append(b)
    routes[b]["routeList"].append(a)

for i in range(N) :
    if(i+1 == 1) :
        for route in routes[i+1]["routeList"] :
            routes[route]["cost"] = 1
            routes[route]["minRoute"] = 1 
    else :
        for route in routes[i+1]["routeList"] :
            currentCost = routes[route]["cost"]
            routes[route]["cost"] = min(routes[route]["cost"], routes[i+1]["cost"] + 1)
            if(currentCost != routes[route]["cost"]) :
                routes[route]["minRoute"] = i+1 
        
    
for i in range(N) :
    if(i+1 == 1) :
        print("Yes")
        continue
    print(routes[i+1]["minRoute"])

Submission status: Wrong Answer

Solution code:
N, M = list(map(int, input().split()))
paths = {}
ans = [0 for i in range(N-1)]
flgs = [False for i in range(N)]
flgs[0] = True
for i in range(M):
    a, b = list(map(int, input().split()))
    if b < a:
        if b in paths:
            paths[b].append(a)
        else:
            paths[b] = [a]
    else:
        if a in paths:
            paths[a].append(b)
        else:
            paths[a] = [b]

paths = sorted(paths.items())

for room_num, room_list in paths:
    if room_num == 1:
        for num in sorted(room_list):
            ans[num-2] = room_num
            flgs[num-1] = True
    else:
        for num in sorted(room_list):
            if flgs[num-1]:
                ans[room_num-2] = num
                flgs[room_num-1] = True

if len(flgs) != sum(flgs):
    print('No')
else:
    print('Yes')
    for num in ans:
        print(num)

Submission status: Wrong Answer

Solution code:
import numpy as np
N, M = map(int, input().split())
ans = [0]*(N+1)
AB_ = []
for _ in range(M):
  AB = sorted(list(map(int, input().split())))
  AB_.append(AB)
  if AB[0] == 1:
    ans[AB[1]] = 1
  elif ans[AB[0]] == 1 and ans[AB[1]]==1:
    continue
  elif ans[AB[0]] == 1:
    ans[AB[1]] = AB[0]
  elif ans[AB[1]] == 1:
    ans[AB[0]] = AB[1]
  elif ans[AB[0]] != 1 and ans[AB[1]] != 1:
    ans[AB[0]] = AB[1]
    ans[AB[1]] = AB[0]

for AB in AB_:
  if AB[0] == 1:
    ans[AB[1]] = 1
  elif ans[AB[0]] == 1 and ans[AB[1]]==1:
    continue
  elif ans[AB[0]] == 1:
    ans[AB[1]] = AB[0]
  elif ans[AB[1]] == 1:
    ans[AB[0]] = AB[1]
  elif ans[AB[0]] != 1 and ans[AB[1]] != 1:
    ans[AB[0]] = AB[1]
    ans[AB[1]] = AB[0]

if 0 in ans[2:]:
  print("No")
else:
  print("Yes")
for i in ans[2:]:
  print(i)

Submission status: Wrong Answer

Solution code:
import math

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


# a[i]とb[i]を比較して、小さい値を書いていく？

print('----')
results = [None] * (n - 1)

for j in range(n):
    for i in range(m):
        if a[i] == j:
            idx = b[i] - 2
            if results[idx] is None:
                results[idx] = j

        elif b[i] == j:
            idx = a[i] - 2
            if results[idx] is None:
                results[idx] = j
 

if None in results:
    print('No')
else:
    print('Yes')
    [print(r) for r in results]

Submission status: Wrong Answer

Solution code:
import copy

N, M = map(int, input().split())
ans = [0]*(N+1)

path = []
check = []
for neveruse in range(M):
    l = list(map(int, input().split()))
    if 1 in l:
        temp = copy.copy(l)
        temp.remove(1)
        ans[temp[0]] = 1
        check.append(temp[0])
    else:
        path.append(l)

while len(check) > 0:
    precheck = copy.copy(check)
    check = []
    for item in path:
        for n in precheck:
            if n in item:
                tmpl = copy.copy(item)

                tmpl.remove(n)

                if ans[tmpl[0]] == 0:
                    ans[tmpl[0]] = n
                    check.append(tmpl[0])
                    path.remove(item)

ans.pop(1)

if ans.count(0) > 1:
    print('No')

else:
    ans[0] = 'Yes'

    for i in range(N):
        print(ans[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
n, m = map(int, input().split())
q = deque()
keys = [0] * n
dic = {i: [] for i in range(n)}
visited = 1
for _ in range(m):
    a, b = map(int, input().split())
    dic[a - 1].append(b - 1)
    dic[b - 1].append(a - 1)

for i in dic[0]:
    q.append(i)
    keys[i] = 1
    visited += 1
while len(q) > 0:
    next = q.popleft()
    for i in dic[next]:
        if i == 0:
            continue
        if keys[i]:
            continue
        if i not in q:
            q.append(i)
            keys[i] = next + 1
            visited += 1
if visited != n:
    print('No')
else:
    print('Yes')
    for i in keys[1:]:
        print(i)

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,-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][0] = 1
    c[b][1] = 1
  if c[a][0] != -1 and c[b][0] == -1:
    c[b][0] = c[a][0] + 1
    c[b][1] = a
  elif c[b][0] != -1 and c[a][0] == -1:
    c[a][0] = c[b][0] + 1
    c[a][1] = b
  elif c[b][0] != -1 and c[a][0] != -1:
    if c[a][0] < c[b][0]:
      c[b][0] = c[a][0] + 1
      c[b][1] = a
    elif c[b][0] < c[a][0]:
      c[a][0] = c[b][0] + 1
      c[a][1] = b
for i in range(M):
  
  a = arr[i][0]
  b = arr[i][1]
  
  if a == 1:
    c[b][0] = 1
    c[b][1] = 1
  if c[a][0] != -1 and c[b][0] == -1:
    c[b][0] = c[a][0] + 1
    c[b][1] = a
  elif c[b][0] != -1 and c[a][0] == -1:
    c[a][0] = c[b][0] + 1
    c[a][1] = b
  elif c[b][0] != -1 and c[a][0] != -1:
    if c[a][0] < c[b][0]:
      c[b][0] = c[a][0] + 1
      c[b][1] = a
    elif c[b][0] < c[a][0]:
      c[a][0] = c[b][0] + 1
      c[a][1] = b        
c[0][0] = 1
ck = 0
for i in range(N+1):
  if c[i][0] == -1:
    ck = 1
if ck == 1:
  print("No")
else:
  print("Yes")
  for i in range(2,N+1):
    print(int(c[i][1]))

Submission status: Wrong Answer

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

a = [0] * m
b = [0] * m

graph = [[float('inf') for j in range(n)] for i in range(n)]

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



size = len(graph)
cost = [float('inf') for _ in range(size)]
visit = [0 for _ in range(size)]
before = [None for _ in range(size)]

cost[0] = 0
while True:
  min_r = float('inf')
  for i in range(size):
    if visit[i] == 0 and cost[i] < min_r:
      x = i
      min_r = cost[x]
  if min_r == float('inf'):
    break
  visit[x] = 1

  for i in range(size):
    if cost[i] > graph[x][i] + cost[x]:
      cost[i] = graph[x][i] + cost[x]
      before[i] = x

i = size - 1
optimum_route = []
while True:
  optimum_route.insert(0, i)
  if i == 0:
    break
  i = before[i]

print(before)

del before[0]

if (None in before):
  print('No')

else:
  print('Yes')
  for i in range(len(before)):
    print(before[i] + 1)

Submission status: Wrong Answer

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

ROOP=[[] for i in range(N+1)]
#部屋2からNまでで、部屋１までの最短経路を出す
#部屋i(2からN)にいるとき、行先は?
for i in range(2,N+1):
	for ab in AB:
		if i ==ab[0]:
			ROOP[i].append(ab[1])

		elif i==ab[1]:
			ROOP[i].append(ab[0])
	if 1 in ROOP[i]:
		GOAL_start=i

#GOALから逆順にDPをしていこう
visited=[-1]*(N+1)
visited[GOAL_start]=1#１に最も近い地点、GOALの距離
#初期設定
#GOALは,1に距離１でいける場所
#こんな感じの再起関数
def bfs(GOAL,GOAL_NEXT):#スタート地点と、そこから行くところ
	if GOAL_NEXT in ROOP[GOAL]:
		ROOP[GOAL].remove(GOAL_NEXT)#GOALに行ける場所を抽出
	else:#もう削除されて通りつくした場合
		return 1
	for i in ROOP[GOAL]:
		if visited[i]==-1 or visited[i]>1+visited[GOAL]:
			visited[i]=1+visited[GOAL]
			bfs(i,GOAL)
		else:
			return 1
bfs(GOAL_start,1)

print(AB)
print(visited)
if -1 not in visited[2:]:
	print("Yes")
	for i in visited[2:]:
		print(i)
else:
	print("NO")

Submission status: Wrong Answer

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

li = []
for i in range(M):
    li.append(list(map(int,input().split())))
ans = [0] * (N+1)
print(ans)
que = [1]
print(li)
def saiki ():
    global que
    global li
    global ans
    print(que)
    q = que.pop(0)
    count = 0
    while True:
        
        if count == len(li):
            break
        print(li)
        print(count)
        if li[count][0] == q and ans[li[count][1]] == 0:
            que.append(li[count][1])
            ans[li[count][1]] = q
            li.pop(count)
        elif li[count][1] == q and ans[li[count][0]] == 0:
            que.append(li[count][0])
            ans[li[count][0]] = q
            li.pop(count)
        else:
            count += 1
    if len(que) == 0:
        for ai in ans:
            if ai != 0:
                print(ai)
    else:
        saiki()

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ans = {i:0 for i in range(1,N+1)}
ans[1] = 10000000
route = {i:[] for i in range(1,N+1)}
for _ in range(M):
    a,b = map(int,input().split())
    route[a].append(b)
    route[b].append(a)
x = {1}
for _ in range(N+1):
    tmp = set()
    for i in x:
        count = 0
        for j in route[i]:
            #print(j)
            if ans[j] == 0:
                ans[j] = i
                count += 1
                tmp.add(j)
    x = tmp
    #print(ans,x)
    if count == 0:
        break
check = 0
for i in ans.keys():
    if i != 1:
        if ans[i] == 0:
            check = 1
if check == 1:
    print('No')
else:
    print('Yes')
    for i in ans.keys():
        if i != 1:
            print(ans[i])

Submission status: Wrong Answer

Solution code:
from _collections import deque


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


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

ans = bfs(0, N, g)
if None in ans:
    print('No')
else:
    print('Yes')
    for j in range(1, len(ans)):
        print(ans[j])

Submission status: Wrong Answer

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

queue = [[1,0]]
isSearched = [float('INF')]*(n+1)
def bfs():
    while(len(queue)>0):
        now,cnt = queue.pop(0)
        if isSearched[now]!=float('INF'):
            continue
        isSearched[now]=cnt
        for i in mp[now]:
            queue.append([i,cnt+1])

bfs()
isOk = True
for i in range(2,n+1):
    if(isSearched[i]==float('INF')):
        isOK = False
        break
if isOk:
    print('Yes')
    for i in range(2,n+1):
        print(isSearched[i])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
def road():
    n,m = map(int,input().split())
    connect = []
    for i in range(m):
        connect.append(list(map(int,input().split())))
    connect.sort(key=lambda x:min(x))
    judge = [0] * n
    for i in range(1,n+1):
        #print(judge[1:])
        if judge[i-1] != 0:
            continue
        elif judge[i-1]==0:
            for road in connect:
                if i == 1:
                    if i == road[0]:
                        judge[road[1]-1] = 1
                    elif i == road[1]:
                        judge[road[0]-1] = 1
                elif i in road and judge[i-1] == 0:
                    if i==road[0] and judge[road[1]-1] !=0:
                        judge[i-1] = road[1]
                    elif i==road[1] and judge[road[0]-1] !=0:
                        judge[i-1] = road[0]
        #print(judge[1:])
    if 0 in judge[1:]:
        print('No')
    else:
        print('Yes')
        for num in judge[1:]:
            print(num)
        #print(judge[1:])
road()

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = map(int,input().split())
graph = [deque([]) for _ in range(N+1)]
for _ in range(M):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)

# 幅優先探索
def bfs(u):
    ans = [None] * (N+1)
    queue = deque([u])
    d = [None] * (N+1) # uからの距離の初期化
    d[u] = 0 # 自分との距離は0
    while queue:
        v = queue.popleft()
        for i in graph[v]:
            if d[i] is None:
                d[i] = d[v] + 1
                ans[i] = v
                queue.append(i)
    return ans
d = bfs(1)
for i in range(2,N+1):
    print(d[i])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


def main():
    N, M = [int(i) for i in input().strip().split()]
    pathes = [[int(i) for i in input().strip().split()] for _ in range(M)]
    ans_table = [[None, float("inf")] for _ in range(N)]
    ans_table[0] = [0, 0]  # next_idx, size to path

    while float("inf") in [dis[1] for dis in ans_table]:
        flag = False
        for path in pathes:
            node_1 = path[0] - 1
            node_2 = path[1] - 1
            if ans_table[node_1][1] != float("inf"):
                cur_dis = ans_table[node_2][1]
                if ans_table[node_1][1] < cur_dis:
                    flag = True
                    ans_table[node_2] = [node_1+1, ans_table[node_1][1] + 1]
            if ans_table[node_2][1] != float("inf"):
                cur_dis = ans_table[node_1][1]
                if ans_table[node_2][1] < cur_dis:
                    flag = True
                    ans_table[node_1] = [node_2 + 1, ans_table[node_2][1] + 1]
        if flag == False:
            print("No")
            return

    print("Yes")

    for ans in ans_table[1:]:
        print(ans[0])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# from math import factorial,sqrt,ceil #,gcd
# from itertools import permutations,combinations,combinations_with_replacement
# from collections import deque,Counter
# import re
# from bisect import bisect_left
# from heapq import heappush,heappop
# from numba import njit
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from fractions import gcd

# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
from networkx import Graph,shortest_path,single_target_shortest_path
G = Graph()
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb,perm #permはnPk

# slist = "abcdefghijklmnopqrstuvwxyz"
N,M = map(int,input().split())

# G.add_nodes_from(list(range(1,N+1)))
for _ in range(M):
    A,B = map(int,input().split())
    G.add_edge(A, B)

# shortestPath = shortest_path(G,target=1)
shortestPath = single_target_shortest_path(G,target=1)
print(shortestPath)
if len(shortestPath) != N:
    print("No")
    exit()

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

# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Wrong Answer

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

q=[0]
d=[0]+[-1]*N
ans=[0]+[-1]*N

while q:
  u=q.pop(0)
  for v in range(M):
    if r[v][0]-1==u:
      o=r[v][1]
      if d[o-1]<=0:
        d[o-1]=d[u]+1
        ans[o-1]=u
        q.append(o-1)
    elif r[v][1]-1==u:
      o=r[v][0]
      if d[o-1]<0:d[o-1]=d[u]+1;q.append(o-1);ans[o-1]=u
print("Yes")
for i in range(1,N):
  print(i+1,ans[i]+1)

Submission status: Wrong Answer

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

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

    ans_list = [-1] * N

    queue = [0]
    seen = [False]*N

    while queue:
        if len(set(seen)) == 1:
            break
        qi = queue.pop(0)
        # qi から 1 遠い頂点が gi
        for gi in g[qi]:
            if seen[gi] == False:
                queue.append(gi)
                if ans_list[gi] == -1:
                    ans_list[gi] = qi
                    seen[gi] = True

    print("Yes")
    for ans in ans_list[1:]:
        print(ans+1)  # 1-index に直す

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
way = [[] for i in range(n + 1)]
ans = [-1 for i in range(n + 1)]
for i in range(m):
    a, b = map(int, input().split())
    way[a].append(b)
    way[b].append(a)
print(way)
reached = []
queue = [1]
while len(queue) > 0:
    go = queue.pop(0)
    reached.append(go)
    for i in range(len(way[go])):
        if (way[go][i] not in reached) and (way[go][i] not in queue):
            queue.append(way[go][i])
            ans[way[go][i]] = go
print('Yes')
for i in range(2, n + 1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

class Cave():
    def __init__(self):
        self.graph = {}
    def add_room(self, r):
        self.graph[r] = []
    def add_passage(self, r1, r2):
        self.graph[r1].append(r2)
        self.graph[r2].append(r1)
    def next_rooms(self, r):
        return self.graph[r]
    def __str__(self):
        return self.graph.__str__()

def main():
    N, M = map(int, input().split())
    AB = [list(map(int, input().split())) for _ in range(M)]

    cave = Cave()
    for i in range(1, N+1):
        cave.add_room(i)
    for r1, r2 in AB:
        cave.add_passage(r1, r2)

    q = deque()
    q.append(1)
    visited = [0]*(N+1)
    visited[1] = -1
    print(1)

    while q:
        r_now = q.popleft()
        for r_next in cave.next_rooms(r_now):
            if visited[r_next] == 0:
                print(r_next)
                visited[r_next] = r_now
                q.append(r_next)

    print('Yes')
    for i in visited[2:]:
        print(i)
main()

Submission status: Wrong Answer

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

Solution code:
N,M = map(int, input().split())
A = []
B = []
tree = [[]] * N

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

for i in range(N):
    if i == 0:
        print("Yes")
        continue
    for i2,v in enumerate(tree):
        if i + 1 in v:
            print(i2 + 1)
            break