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:
import math
from queue import Queue

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

gh = {}
for i in range(m):
    p1, p2 = map(int, input().split(" "))
    if p1 in gh:
        gh[p1].append(p2)
    else:
        gh[p1] = [p2]

    if p2 in gh:
        gh[p2].append(p1)
    else:
        gh[p2] = [p1]

_mp = [-1 for _ in range(n)]
_mp[0] = 0
q = Queue()
q.put(1)

while q.qsize() != 0:
    cp = q.get()
    for p in gh[cp]:
        if _mp[p - 1] != -1: continue
        q.put(p)
        _mp[p - 1] = _mp[cp - 1] + 1

for k, v in gh.items():
    if len(v) == 0:
        print("No")
        exit()

print("Yes")
for mpi in _mp[1:]:
    print(mpi)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
connections = [list(map(int, input().split())) for _ in range(m)]
weights = [2e5 + 10] * n
weights[0] = 1
directions = [1] * n
for _ in range(m):
    for con in connections:
        r1 = con[0]
        r2 = con[1]
        w1 = weights[r1 - 1]
        w2 = weights[r2 - 1]
        if w1 < 2e5 + 10 and w1 + 1 < w2:
            weights[r2 - 1] = w1 + 1
            directions[r2 - 1] = r1
        if w2 < 2e5 + 10 and w2 + 1 < w1:
            weights[r1 - 1] = w2 + 1
            directions[r1 - 1] = r2

if max(weights) > 2e5 + 5:
    print("No")
else:
    for d in directions:
        print(d)

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
root=[[] for _ in range(n)]
for i in range(m):
	a,b=map(int,input().split())
	root[a-1].append(b-1)
	root[b-1].append(a-1)
times=[0]*n
sign=[-1]*n
sign[0]=0
que=deque([0])
while que:
	q=que.popleft()
	for i in root[q]:
		if sign[i]==-1:
			sign[i]=q
			que.extend(root[i])
for i in range(n-1):
	print(sign[i+1]+1)

Submission status: Wrong Answer

Solution code:
n,m=list(map(int, input().split()))
a=[]
b=[]
answer=[0]*n
answer[0]=1
for i in range(m):
    c=list(map(int, input().split()))
    a.append(c[0])
    b.append(c[1])
count=1#最初から1の部屋はOKにしとく
queue=[1]
newqueue=[]
while(count<n and len(queue)!=0):
    for k in range(m):
        for j in queue:
            if(a[k]==j):
                if(answer[b[k]-1]==0):
                    answer[b[k]-1]=j
                    count+=1
                    newqueue.append(b[k])
            elif(b[k]==j+1):
                if(answer[a[k]-1]==0):
                    answer[a[k]-1]=j
                    count+=1
                    newqueue.append(a[k])
    queue=newqueue
    newqueue=[]
if(count<n):
    print('No')
else:
    print('Yes')
    for l in range(n-1):
        print(answer[l+1])

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))

n,m=getNM()
a=[]
b=[]
c=[0]*(n+1)
x=[]
for i in range(m):
    a1,b1=getNM()
    a.append(a1)
    b.append(b1)
    if a1==1:
        c[b1]=1
        x.append(b1)
    elif b1==1:
        c[a1]=1
        x.append(a1)


for i in range(1,n):
    xxx=c.copy()
    for j in range(m):
        #print(i,j)
        if c[a[j]]==i and c[b[j]]==0:
            c[b[j]]=a[j]
        elif c[b[j]]==i and c[a[j]]==0:
            c[a[j]]=b[j]
        #print(c)
    if xxx[2:]==c[2:]:
        break

if 0 in c[2:]:
    print('No')
    exit()
print('Yes')
for i in range(n-1):
    print(c[2:][i])

Submission status: Wrong Answer

Solution code:
import queue
n,m=map(int,input().split())
root=[[0 for i in range(n)] for i in range(n)]
for i in range(m):
    a,b=map(int,input().split())
    root[a-1][b-1]=1
    root[b-1][a-1]=1
min=[-1 for i in range(n)]
min[0]=2
dict={}
for i in range(n):
    dict[i]=-1

start=0
check=[False]*n
toVis=queue.Queue()
check[start]=True
for i in range(len(root[0])):
    if root[0][i]==1:
        toVis.put(i)
        dict[i]=start
     #   print(i,":",start)
        check[i]=True
while(toVis.empty()!=True):
    now=toVis.get()
    #print(now)
    check[now]=True
    for i in range(n):
        if root[now][i]==1 and check[i]==False:
            toVis.put(i)
            dict[i]=now
           # print(i,":",now)
            check[i]=True
print(dict)  
for i in range(1,n):
    if dict[i]==-1:
        print("No")
        exit()
print("Yes")
for i in range(1,n):
    print(dict[i]+1)

Submission status: Wrong Answer

Solution code:
import numpy as np
import copy

NM = [int(x) for x in input().split()]
M=[]
for i in range(NM[1]):
  M.append([int(x) for x in input().split()])

X=np.zeros(NM[0])
Y=np.zeros(NM[0])
target=1
list_target=[1]
list_target_d=[1]
for i in range(NM[1]):
  for j in range(NM[1]):
    for k in range(2):
      if M[j][k] in list_target and not M[j][k-1] in list_target:
        target=M[j][k-1]
        X[target-1]=i+1
        Y[target-1]=M[j][k]
        list_target_d.append(target)
  list_target=copy.copy(list_target_d)
if np.count_nonzero(X ==0)>2:
  print("No")
else:
  print("Yes")
  for i in range(1,NM[0]):
    print(Y[i])
    
"""
6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6
Yes
6
5
5
1
1
"""

Submission status: Wrong Answer

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

def search( src, find_val, idx_find, idx_cur = []):
    if isinstance( src, list):
        for i, v in enumerate(src):
            search( v, find_val, idx_find, idx_cur + [i])
    else:
        if src == find_val:
            idx_find.append( idx_cur)

def test(  arr):
    idx_find = []
    for i in range(N+1):
        search( arr, i, idx_find)
    print(idx_find)

test(lst)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

n, m = map(int,input().split())
p = [list(map(int,input().split())) for i in range(m)]
'''l = [[] for i in range(m+1)]
for pi in p:
    l[pi[0]].append(pi[1])
    l[pi[1]].append(pi[0])
l.pop(0)'''
l = [[0]*n for i in range(n)]
for pi in p:
    l[pi[0]-1][pi[1]-1] = 1
    l[pi[1]-1][pi[0]-1] = 1
l = np.array(l)

#最短経路を求める
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]

d, p = shortest_path(l, return_predecessors=True)

#for i in range(1,n):
    #print(get_path(0, i, p))

print("Yes")
ans = d[0][1:]
for i in ans:
    print(int(i))

#最短経路を求める

Submission status: Wrong Answer

Solution code:
from queue import Queue
N, M = map(int, input().split())

root = [[] for _ in range(N)]
#print(root)
for i in range(M):
    A, B = map(int, input().split())
    root[A-1].insert(len(root[A-1]), B)
    root[B-1].insert(len(root[B-1]), A)
room = [0]*N

q = Queue()
for k in root[0]:
    room[k-1] = 1
    q.put(k)
while not q.empty():
    a = q.get()
    for j in root[a-1]:
        if room[j-1] == 0:
            q.put(j)
            room[j-1] = a
if 0 in room[1:]:
    print("No")
else:
    for ans in room[1:]:
        print(ans)

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))
            
if -1 in ans[1:]:
    print('No')
else:
    print('Yes')
    for i in range(2,N+1):
        print(ans[i])

Submission status: Wrong Answer

Solution code:
N, M = [ int(i) for i in input().strip().split(' ')]

miti = [0] * (N - 1)
path = { i:set() for i in range(1, N+1)}
routes = []
for i in range(M):
    Ai, Bi = [ int(i) for i in input().strip().split(' ')]
    path[Ai].add(Bi)
    path[Bi].add(Ai)

targets = set([1])
check_list = set([1])

while True:
    for target in targets:
        targets = []
        for t in path[target]:
            if miti[t-2] == 0:
                miti[t-2] = target
        targets += path[target]
        check_list.add(target)
    targets = set(targets) - check_list
    if len(check_list) == N:
        break
if min(miti) == 0:
    print('No')
else:
    print('Yes')
    for mt in miti:
        print(mt)

Submission status: Wrong Answer

Solution code:
# 2020/05/17
# AtCoder Beginner Contest 168 - D

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

plist = [[] for k in range(n+1)]
print(len(plist))
for i in range(m):
    a, b = map(int, input().split())
    plist[a].append(b)
    plist[b].append(a)

visited = [0] * (n+1)
visited[0] = 10 ** 9

beforeidx = [0] * (n+1)

# BFS
q = list()
q.append(1)

while(len(q) > 0):
    stidx = q.pop(0)
    for j in range(len(plist[stidx])):
        nextidx = plist[stidx][j]
        if visited[nextidx] == 0:
            q.append(nextidx)
            beforeidx[nextidx] = stidx
            visited[nextidx] = 1

if min(visited) > 0:
    print('Yes')
    for i in range(2, n+1):
        print(beforeidx[i])
else:
    print('No')

Submission status: Wrong Answer

Solution code:

def func(i, d, marks):
    rooms = numpy.nonzero(d[i])[0]
    new_room = []
    if rooms.size == 0:
        return marks
    for j in rooms:
        room_idx = j
        if room_idx in marks:
            continue
        marks[room_idx] = i
        new_room.append(room_idx)
    for j in new_room:
        marks = func(j, d, marks)
    return marks

def get_input():
    N, M =  list(map(int, input().split()))
    d = numpy.zeros((N,N))
    for i in range(M):
        a, b =  list(map(int, input().split()))
        d[a-1, b-1] = 1
        d[b-1, a-1] = 1
    return N, M, d

def write_result(marks, N):
    flag = True
    output_str = ''
    for i in range(1, N):
        if i not in marks:
            flag = False
            break
        output_str += f'{marks[i]+1}\n'
    if flag:
        print('Yes')    
        print(output_str)
    else:
        print('No')

import numpy

marks = {0:0}
try:
    N, M, d = get_input()
    marks = func(0, d, {0: 0})
    write_result(marks, N)
except:
    pass

Submission status: Wrong Answer

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


for i in range(M):
    if AB[i][0] == 1:
         sign[AB[i][1]-2] = 1
    elif AB[i][1] == 1:
         sign[AB[i][0]-2] = 1

#for i in range(M):
#    if sign[AB[i][0]-2] == 1 and sign[AB[i][1]-2] != 1:
#        sign[AB[i][1]-2] = AB[i][0]
#    elif sign[AB[i][1]-2] == 1 and sign[AB[i][0]-2] != 1:
#        sign[AB[i][0]-2] = AB[i][1]
for i in range(100):
    for i in range(M):
        if sign[AB[i][0]-2] != 0 and sign[AB[i][1]-2] == 0:
            sign[AB[i][1]-2] = AB[i][0]
        elif sign[AB[i][1]-2] != 0 and sign[AB[i][0]-2] == 0:
            sign[AB[i][0]-2] = AB[i][1]

if sign.count(0) > 0:
    print("No")
else:
    print("Yes")
    for number in sign:
        print(number)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

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

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

for i in range(len(route)):
    for j in route[i]:
        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:
# input
N, M = map(int, input().split())
Load = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    Load[a].append(b)
    Load[b].append(a)

print(Load)

# process
result = True
sign = [-1]*N
l = [0]
while True:
    for i in l:
        l_ = []
        for j in Load[i]:
            if j == i:
                continue

            if sign[j] == -1:
                sign[j] = i
            l_.append(j)
    print(sign)
    if not -1 in sign:
        break

    l = l_

sign.pop(0)

# output
print("Yes" if result else "No")
[print(x+1) for x in sign]

Submission status: Wrong Answer

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

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

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):#要素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が属するグループと要素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):#要素xが属するグループのサイズ（要素数）を返す
        return -self.parents[self.find(x)]

    def same(self, x, y):#要素x, yが同じグループに属するかどうかを返す

        return self.find(x) == self.find(y)

    def members(self, x):#要素xが属するグループに属する要素をリストで返す
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):#すべての根の要素をリストで返す
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):#グループの数を返す
        return len(self.roots())

    def all_group_members(self):#all_group_members O(N)かかるので注意
        return {r: self.members(r) for r in self.roots()}

uf=UnionFind(n+1)

for i in range(m):
    a=ab[i][0]
    b=ab[i][1]
    if uf.same(a,b)==False:
        uf.union(a,b)

#print(uf.all_group_members())
#print(uf.size(2))
if uf.group_count()!=2:
    print("NO")
    exit()

for i in range(m):
    ab[i].append(1)


def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d

################################
#print(ab[0])
cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(m):
    x,y,z = ab[i]
    cost[x-1][y-1] = z
    cost[y-1][x-1] = z
ans=dijkstra(0,n,m,cost)
#print(ans)
print("Yes")
for i in range(1,n):
    print(ans[i])

Submission status: Wrong Answer

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


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


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


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

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


for i in before:
    print(i+1)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

def bfs(u):
    
    q = deque()
    q.append(u)
    while q:
        r = q.pop()
        for v in R[r]:
            if V[v]:
                V[v] = False
                S[v] = r
                q.append(v)

S = [-1] * N
S[0] = 0
V = [True] * N  # Visited

bfs(0)

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

Submission status: Wrong Answer

Solution code:
import queue
n,m=map(int,input().split())
root=[[0 for i in range(n)] for i in range(n)]
for i in range(m):
    a,b=map(int,input().split())
    root[a-1][b-1]=1
    root[b-1][a-1]=1
min=[-1 for i in range(n)]
min[0]=2
dict={}
for i in range(n):
    dict[i]=-1

start=0
check=[False]*n
toVis=queue.Queue()
check[start]=True
for i in range(len(root[0])):
    if root[0][i]==1:
        toVis.put(i)
        dict[i]=start
     #   print(i,":",start)
        check[i]=True
while(toVis.empty()!=True):
    now=toVis.get()
    #print(now)
    check[now]=True
    for i in range(n):
        if root[now][i]==1 and check[i]==False:
            toVis.put(i)
            dict[i]=now
           # print(i,":",now)
            check[i]=True
print(dict)  
for i in range(1,n):
    print(dict[i]+1)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))

n,m=getNM()
a=[]
b=[]
c=[0]*(n+1)
x=[]
for i in range(m):
    a1,b1=getNM()
    a.append(a1)
    b.append(b1)
    if a1==1:
        c[b1]=1
        x.append(b1)
    elif b1==1:
        c[a1]=1
        x.append(a1)


for i in range(1,n):
    xxx=c
    for j in range(m):
        #print(i,j)
        if c[a[j]]==i and c[b[j]]==0:
            c[b[j]]=a[j]
        elif c[b[j]]==i and c[a[j]]==0:
            c[a[j]]=b[j]
        #print(c)
    if xxx[2:]==c[2:]:
        break

if 0 in c[2:]:
    print('No')
    exit()
print('Yes')
for i in range(n-1):
    print(c[2:][i])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

def input_one_number():
    return int(input())

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

def input_multiple_number_as_list():
    return list(map(int, input().split()))



N,M = input_multiple_number()

A = [0]*M
B = [0]*M
ans = [0]*(N-1)

for i in range(M):
	A[i],B[i] = input_multiple_number()



def DFS(K):

	michi = []
	for i in range(len(A)):
		if A[i] == K:
			if ans[B[i]-1-1] == 0:
				ans[B[i]-1-1] = K
				michi.append(B[i])
		elif B[i] == K:
			if ans[A[i]-1-1] == 0:
				ans[A[i]-1-1] = K
				michi.append(A[i])

	for i in michi:
		DFS(i)

DFS(1)
print(ans)

Submission status: Wrong Answer

Solution code:
"""
import random
import functools
import copy
import bisect
import array
import re
import collections
import heapq
import fractions
import itertools
import string
import math
from operator import itemgetter as ig
from bisect import bisect_left, bisect_right, insort_left, insort_right
from itertools import permutations, combinations, product, accumulate, groupby
from heapq import heappush, heappop
from collections import deque, defaultdict, Counter
import sys
sys.setrecursionlimit(10 ** 7)
# import numpy as np

inf = 10 ** 20
INF = float("INF")
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]
ddn9 = ddn + [(0, 0)]
'''for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:'''
"""

import math
from collections import deque, defaultdict
import sys
sys.setrecursionlimit(10 ** 7)


def wi(): return list(map(int, sys.stdin.readline().split()))
# WideIntPoint


def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]


def ws(): return sys.stdin.readline().split()


def si(): return int(sys.stdin.readline())  # SingleInt


def ss(): return input()


def hi(n): return [si() for _ in range(n)]


def hs(n): return [ss() for _ in range(n)]  # HeightString


def s_list(): return list(input())


def mi(n): return [wi() for _ in range(n)]  # MatrixInt


def mip(n): return [wip() for _ in range(n)]


def ms(n): return [ws() for _ in range(n)]


def num_grid(n): return [[int(i) for i in sys.stdin.readline().split()[
    0]] for _ in range(n)]  # NumberGrid


def grid(n): return [s_list() for _ in range(n)]


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def round_up(a, b):
    """ a/b の切り上げ """
    c = (a + b - 1) / b
    return c


def lcm(a, b):
    """a,bの最小公倍数"""
    return a * b // gcd(a, b)


def floor(a, b):
    """floor(a/b) 整数値を返す"""
    c = (a - a % b)/b
    return int(c)


def main():
    N, M = wi()
    G = defaultdict(list)
    for i in range(M):
        a, b = map(int, input().split())
        G[a].append(b)
        G[b].append(a)

    #print(G)
    q = deque()
    q.append(1)
    visit = [False]*N
    dis = [-1] * N
    dis[0] = 0
    while q:
        p = q.popleft()
        visit[p-1] = True
        for n_p in G[p]:
            if visit[n_p-1] != True:
                dis[n_p-1] = dis[p-1] + 1
                visit[n_p-1] = True
                q.append(n_p)

    if all(visit) == True:
        print('Yes')
        for i in range(2, N+1):
            print(dis[i-1])
    else:
        print('No')


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
from sys import setrecursionlimit
import math
setrecursionlimit(10 ** 7)

n,m = map(int,stdin.readline().rstrip().split())
li = [[]for _ in range(n)]
lin = []

for i in range(m):
    a,b = map(int,stdin.readline().rstrip().split())
    a -= 1
    b -= 1
    li[a].append(b)
    li[b].append(a)
    lin.append([a,b])

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n)]
        self.rank = [0] * n
        self.size = [1] * n
    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
    # 同じ集合に属するか判定
    def same(self, x, y):
        return self.find(x) == self.find(y)
    # すべての頂点に対して親を検索する
    def all_find(self):
        for n in range(len(self.par)):
            self.find(n)

#深さ優先探索DFS
def depth_first_search(start, W):
    # リストをスタックとして利用する
    work_stack = []
    visited = set()
    work_stack.append(start)
    visited.add(start)
    while work_stack:
        print(work_stack)  # work_stackの中身を表示する
        here = work_stack.pop()
        for i, node in enumerate(W[here]):
            if node == 0: continue
            if i not in visited:
                work_stack.append(i)
                visited.add(i)
    return visited

uni = UnionFind(n)

lis = [0]*n
visited = [False]*n
visited[0] = True
oya = 0
def keiro(now):
    ima = li[now]
    for i in ima:
        if visited[i]:
            continue
        else:
            lis[i] = now
            visited[i] = True
            keiro(i)

keiro(0)
print("Yes")
for i in lis[1:]:
    print(i+1)

print(lis)

Submission status: Wrong Answer

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

N, M = map(int, input().split())
l = [[0]*N for _ in range(N)]
for _ in range(M):
    A, B = map(int, input().split())
    l[A-1][B-1] = 1
    l[B-1][A-1] = 1
    
a = np.array(l)
aa = shortest_path(a, directed=False)

if float('inf') in aa[0]:
    print('No')
else:
    print('Yes')
    for i in aa[0][1:]:
        print(int(i))

Submission status: Wrong Answer

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


    res = {i: False for i in range(2, N+1)}
    determined = [1]
    current_level = [1]
    next_level = []

    while True:

        for a, b in AB:
            if a in current_level and b not in determined:
                res[b] = a
                next_level.append(b)
                continue
            elif a not in determined and b in current_level:
                res[a] = b
                next_level.append(a)

        determined.extend(next_level)
        if False not in res.values():
            return True, res
            break
        if len(next_level) == 0:
            return False, res

        current_level = next_level
        next_level = []
    
    
solved, res = solver()
if solved:
    print('YES')
    for key in sorted(res.keys()):
        print(res[key])
else:
    print('NO')

Submission status: Wrong Answer

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

print('YES')

#print(edge)
q = deque([0])

tmp = [-1]*N#部屋１からの距離
tmp[0] = 0

while q:
    now = q.popleft()
    for v in edge[now]:
        if tmp[v] != -1:
            tmp[v] = min(tmp[v],tmp[now]+1)
            continue
        tmp[v] = tmp[now] + 1
        q.append(v)
for c in tmp[1:]:
    print(c)

Submission status: Wrong Answer

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

INF = 10**10


def search(table, visit, current, cnt):
    if visit[current] < cnt:
        return
    visit[current] = cnt
    for x in table[current]:
        search(table, visit, x, cnt+1)


def main(input, print):
    n, m = map(int, input().split())
    table = [[] for _ in range(n+1)]
    visit = [INF]*(n+1)
    for i in range(m):
        a, b = map(int, input().split())
        table[a].append(b)
        table[b].append(a)
    search(table, visit, 1, 0)
    is_ok = True
    for i in range(2, n+1):
        if visit[i] == INF:
            is_ok = False
            break
    if is_ok:
        print('Yes')
        for i in range(2, n+1):
            print(visit[i])
    else:
        print('No')


if __name__ == '__main__':
    main(sys.stdin.readline, print)

Submission status: Wrong Answer

Solution code:
import networkx as nx
n,m=map(int,input().split())
g = nx.Graph()
for _ in range(m):
    x,y=map(int,input().split())
    g.add_edge(x,y)

Submission status: Wrong Answer

Solution code:
from queue import Queue

n, m = map(int, input().split())
d = {x: [] for x in range(n)}
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    d[a].append(b)
    d[b].append(a)

visited = [False for x in range(n)]
distance = [float("inf") for x in range(n)]
distance[0] = 0
que = Queue()
que.put(0)
while not que.empty():
    now = que.get()
    if visited[now]:
        continue
    visited[now] = True
    for _next in d[now]:
        if visited[_next]: continue
        distance[_next] = min(distance[_next], distance[now] + 1)
        que.put(_next)
print("Yes")
for i in distance[1:]:
    print(i)

Submission status: Wrong Answer

Solution code:
import heapq
import sys

input = sys.stdin.readline

def Dijkstra_heap(s, edge):
    # 始点sから各頂点への最短距離#始点sから各頂点への最短距離
    d = [10**6] * n
    used = [False] * n
    d[s] = 0
    used[s] = True
    edgelist = []
    for i, j in edge[s]:
        heapq.heappush(edgelist, i+j*(10**6))
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v = minedge % (10**6)
        # まだ使われてない頂点の中から最小の距離のものを探す
        if used[v]: continue
        d[v] = minedge // (10**6)
        used[v] = True
        for e in edge[v]:
            if not used[e[0]]:
                heapq.heappush(edgelist, e[0]+(e[1]+d[v]) * (10**6))
    return d

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

for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    edge[a].append((b, 1))
    edge[b].append((a, 1))
# 頂点iまでの最短距離
dist = Dijkstra_heap(0, edge)
if 10**6 in dist:
  print("No")
  exit()
print("Yes")
for i in dist[1:]:
  print(i)

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(M):
    for i in x:
        tmp = []
        for j in route[i]:
            #print(j)
            count = 0
            if ans[j] == 0:
                ans[j] = i
                count += 1
            tmp.append(j)
    x = tmp
    #print(ans,x)
    if count == 0:
        break
print('Yes')
for i in ans.keys():
    if i != 1:
        print(ans[i])