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:
from collections import deque

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

graph = [[] for _ in range(n + 1)]
for i in range(m):
    a = ab[i][0]
    b = ab[i][1]
    graph[a].append(b)
    graph[b].append(a)

inf = 100100100
ans = [[inf, inf] for _ in range(n + 1)]
ans[0] = [0, 0]
ans[1] = [0, 0]

q = deque([1])
while q:
    now = q.popleft()
    depth = ans[now][1]
    for x in graph[now]:
        if ans[x][0] == inf:
            q.append(x)
            if ans[x][1] > depth + 1:
                ans[x][0] = now
                ans[x][1] = depth + 1

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

Submission status: Wrong Answer

Solution code:
from collections import deque

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

graph = [[] for _ in range(n + 1)]
for i in range(m):
    a = ab[i][0]
    b = ab[i][1]
    graph[a].append(b)
    graph[b].append(a)

inf = 100100100
ans = [[inf, inf] for _ in range(n + 1)]
ans[0] = [0, 0]
ans[1] = [0, 0]

q = deque([1])
while q:
    now = q.popleft()
    depth = ans[now][1]
    for x in graph[now]:
        if ans[x][0] == inf:
            q.append(x)
            if ans[x][1] > depth + 1:
                ans[x][0] = now
                ans[x][1] = depth + 1

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

Submission status: Wrong Answer

Solution code:
import networkx as nx
n,m=map(int,input().split())
s=[list(map(int,input().split())) for i in range(m)]

g=nx.Graph()
g.add_nodes_from([i for i in range(1,n+1)])

for x in s:
    g.add_edge(x[0],x[1])
di=nx.predecessor(g,source=1)
print(di)
if len(di)!=n:
    print("No")
    exit()

print("Yes")
for x in range(2,n+1):
    print(di[x][0])

Submission status: Wrong Answer

Solution code:
import sys
from io import StringIO
import unittest
from collections import deque


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

    graph = [[] for _ in range(n)]
    ans = [-1 for _ in range(n - 1)]

    for a, b in ab:
        graph[a - 1].append(b)
        graph[b - 1].append(a)

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

    d = deque()
    d.append([1, graph[0]])

    while d:
        node, l = d.popleft()

        for i in l:
            if depth[i - 1] == -1:
                depth[i - 1] = depth[node - 1] + 1
                d.append([i, graph[i - 1]])

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

    for a, b in ab:
        if abs(depth[a - 1] - depth[b - 1]) == 1:
            if ans[a - 2] == -1:
                ans[a - 2] = b
            if ans[b - 2] == -1:
                ans[b - 2] = a

    if -1 in set(ans):
        print('No')
    else:
        print('Yes')
        for a in ans:
            print(a)


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """4 4
1 2
2 3
3 4
4 2"""
        output = """Yes
1
2
2"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6"""
        output = """Yes
6
5
5
1
1"""
        self.assertIO(input, output)


if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Wrong Answer

Solution code:
from collections import deque

# print('input >>')
N, M = map(int,(input().split()))
ABs = [map(int,(input().split())) for _ in range(M)]

INF = 10 ** 10
ds = [INF] * (N+1)
marks = [0] * (N+1)

nodes = [None] * (N+1)

for AB in ABs:
    A, B = AB
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

    B, A = A, B
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

# print(nodes)

queue = deque([1])
visited = [0] * (N+1)
visited[1] = 1

# d = 0
# ds = [INF] * (N+1)
marks = [0] * (N+1)
parent = 1

while len(queue) > 0:
    p = queue.popleft()
    # print(p)
    # parent, node = p[0], p[1]
    # visited[node] = 1
    # marks[node] = parent
    for n in nodes[p]:
        if visited[n] == 0:
            visited[n] = 1
            marks[n] = p

print('Yes')
for mark in marks[2:]:
    print(mark)

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[1]
count = 0
for j in range(M-1):
    for visit in nextvisit[j]:
        erase = []
        for k in range(len(L)):
    
            
            if visit == L[k][1] and (L[k][0] not in visited):
                nextvisit[j+1].append(L[k][0])
                visited.append(L[k][1])
                visited.append(L[k][0])
                room[L[k][0]-1] = L[k][1]
                erase.append(k)
                count +=1
            if visit == L[k][0] and (L[k][1] not in visited):
                nextvisit[j+1].append(L[k][1])
                visited.append(L[k][0])
                visited.append(L[k][1])
                room[L[k][1]-1] = L[k][0]
                erase.append(k)
                count+=1
        erasecount = 0
        for j in erase:
            del L[j-erasecount]
            erasecount+=1
    if count > N:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==1:
    print(1)

Submission status: Wrong Answer

Solution code:
from collections import deque

# print('input >>')
N, M = map(int,(input().split()))
ABs = [map(int,(input().split())) for _ in range(M)]

INF = 10 ** 10
ds = [INF] * (N+1)
marks = [0] * (N+1)

nodes = [None] * (N+1)

for AB in ABs:
    A, B = AB
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

    B, A = A, B
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

# print(nodes)

queue = deque()
for node in nodes[1]:
    queue.append((1, node))
visited = [0] * (N+1)
visited[1] = 1

# d = 0
# ds = [INF] * (N+1)
marks = [0] * (N+1)
parent = 1

while len(queue) > 0:
    p = queue.popleft()
    # print(p)
    parent, node = p[0], p[1]
    visited[node] = 1
    marks[node] = parent
    for n in nodes[node]:
        if visited[n] == 0:
            visited[n] = 1
            queue.append((node, n))

print('Yes')
for mark in marks[2:]:
    print(mark)

Submission status: Wrong Answer

Solution code:
from collections import Counter 
from collections import defaultdict
from collections import deque
from functools import reduce
import math
import itertools
import heapq
import numpy as np
import sys
sys.setrecursionlimit(10**6)

#n=int(input())
#n,m=list(map(int,input().split()))
#a=list(map(int,input().split()))
ceil=lambda x,y: (x+y-1)//y
input_list = lambda : list(map(int,input().split()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    check=[False for _ in range(n)]
    queue=[-1 for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    last_ind=1
    while last_ind<n:
        
        if now>=n:
            return []
        if check[queue[now]]:
            now+=1
            continue
        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if check[edge]:
                continue

            queue[last_ind]=edge
            last_ind+=1
            check[edge]=True
            
            ans[edge]=queue[now]
        check[queue[now]]=True
        now+=1
    return ans



n,m=input_list()
node=[[] for _ in range(n)]
for i in range(m):
    u,v=input_list()
    u-=1
    v-=1
    node[u].append([v,i])
    node[v].append([u,i])

#print(np.array(node))

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

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

Submission status: Wrong Answer

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

abj = [set() for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    abj[a].add(b)
    abj[b].add(a)
    
def bfs_paths(graph, start, goal):
    queue = [(start, [start])]
    result = []

    while queue:
        n, path = queue.pop(0)
        if n == goal:
            result.append(path)
        else:
            for m in graph[n] - set(path):
                queue.append((m, path + [m]))
    return result


if all([bfs_paths(abj, i, 0)[0][-1] == 0 for i in range(n)]):
    print('yes')
    for i in range(1,n):
        print(bfs_paths(abj, i, 0)[0][1]+1)
else:
    print('No')

Submission status: Wrong Answer

Solution code:
# list(map(int, input().split()))
# int(input())
def main(AB, N, M):
    def serch(st = {1}, lst = [1] + [0] * (N-1)):
        while st > 0:
            next_st = set([])
            for n in st:
                if len(AB[n]) == 0:
                    print('No')
                    exit()
                else:
                    for ab in AB[n]:
                        if lst[ab - 1] == 0:
                            lst[ab - 1] = n
                            next_st.add(ab)
            return serch(next_st, lst)
        else:
            return lst
    try:
        ans = serch()
    except:
        print('No')
        exit()
        
    if 0 in set(ans[1:]):
        print('No')
    else:
        print('Yes')
        [print(i) for i in ans[1:]]


if __name__ == '__main__':
    N, M = list(map(int, input().split()))
    AB = {i+1:[] for i in range(N)}
    for _ in range(M):
        a, b = list(map(int, input().split()))
        AB[a].append(b)
        AB[b].append(a)
    main(AB, N, M)

Submission status: Wrong Answer

Solution code:
from collections import deque

# print('input >>')
N, M = map(int,(input().split()))
ABs = [map(int,(input().split())) for _ in range(M)]

INF = 10 ** 10
ds = [INF] * (N+1)
marks = [0] * (N+1)

nodes = [None] * (N+1)

for AB in ABs:
    A, B = AB
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

    B, A = A, B
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

# print(nodes)

queue = deque()
for node in nodes[1]:
    queue.append((1, node))
visited = [0] * (N+1)
visited[1] = 0

# d = 0
# ds = [INF] * (N+1)
marks = [0] * (N+1)
parent = 1

while len(queue) > 0:
    p = queue.popleft()
    # print(p)
    parent, node = p[0], p[1]
    visited[node] = 1
    marks[node] = parent
    for n in nodes[node]:
        if visited[n] == 0:
            visited[n] = 1
            queue.append((node, n))

print('Yes')
for mark in marks[2:]:
    print(mark)

Submission status: Wrong Answer

Solution code:
from collections import Counter 
from collections import defaultdict
from collections import deque
from functools import reduce
import math
import itertools
import heapq
import numpy as np
import sys
sys.setrecursionlimit(10**6)

#n=int(input())
#n,m=list(map(int,input().split()))
#a=list(map(int,input().split()))
ceil=lambda x,y: (x+y-1)//y
input_list = lambda : list(map(int,input().split()))



#bfs内で処理すると使い回しが効かないのでsearch_color とか幅探索後の具体的な処理は別個にしたほうがいい
def bfs(s,n,node):
    check=[False for _ in range(n)]
    check[0]=True
    queue=[-1 for _ in range(n)]
    now=0
    queue[now]=s
    ans=[-1 for _ in range(n)]
    ans[0]=[0]
    last_ind=1
    while last_ind<n:
        
        if now>=n:
            return []
        if check[queue[now]]:
            now+=1
            continue
        for i in node[queue[now]]:
            edge=i[0]
            
            ind=i[1]
            if check[edge]==True:
                continue

            queue[last_ind]=edge
            last_ind+=1
            check[edge]=True
            
            ans[edge]=queue[now]
        now+=1
    return ans



n,m=input_list()
node=[[] for _ in range(n)]
for i in range(m):
    u,v=input_list()
    u-=1
    v-=1
    node[u].append([v,i])
    node[v].append([u,i])

#print(np.array(node))

ans=bfs(0,n,node)
if len(ans)==0:
    print("No")
    exit()

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

Submission status: Wrong Answer

Solution code:
from collections import deque

# print('input >>')
N, M = map(int,(input().split()))
ABs = [map(int,(input().split())) for _ in range(M)]

INF = 10 ** 10
ds = [INF] * (N+1)
marks = [0] * (N+1)

nodes = [None] * (N+1)

for AB in ABs:
    A, B = AB
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

    B, A = A, B
    if nodes[A] is None:
        nodes[A] = []
    nodes[A].append(B)

# print(nodes)

queue = deque()
for node in nodes[1]:
    queue.append((1, node))
visited = [0] * (N+1)
visited[1] = 0

# d = 0
# ds = [INF] * (N+1)
marks = [0] * (N+1)
parent = 1

while len(queue) > 0:
    p = queue.popleft()
    # print(p)
    parent, node = p[0], p[1]
    visited[node] = 1
    marks[node] = parent
    for n in nodes[node]:
        if visited[n] == 0:
            visited[n] = 1
            queue.append((node, n))

for mark in marks[2:]:
    print(mark)

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=list(map(int,input().split()))
A=[list(map(int,input().split())) for i in range(M)]
graph=[[]for i in range(N+1)]
for i in range(M):
    u,v=A[i]
    graph[u].append(v)
    graph[v].append(u)

stack=deque([1])
visited=[-1 for i in range(N+1)]
visited2=[-1 for i in range(N+1)]
visited[1]=0

while stack:
    x=stack.popleft()
    for i in graph[x]:
        if visited[i]==-1:
            visited[i]=visited[x]+1
            visited2[i]=x
            stack.appendleft(i)
print('Yes')
print(*visited2[2:],sep='\n')

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[1]
count = 0
for j in range(M-1):
    for visit in nextvisit[j]:
        for k in range(len(L)):
            erase = []
            if visit == L[k][1] and (L[k][0] not in visited):
                nextvisit[j+1].append(L[k][0])
                visited.append(L[k][1])
                visited.append(L[k][0])
                room[L[k][0]-1] = L[k][1]
                erase.append(k)
                count +=1
            if visit == L[k][0] and (L[k][1] not in visited):
                nextvisit[j+1].append(L[k][1])
                visited.append(L[k][0])
                visited.append(L[k][1])
                room[L[k][1]-1] = L[k][0]
                erase.append(k)
                count+=1
        for j in erase:
            del L[j]
    if count > N:
        break
print("Yes")
if N >2:
    for k in range(1, N):
        print(room[k])
if N ==1:
    print(1)

Submission status: Wrong Answer

Solution code:
from collections import deque
n,m=map(int,input().split())
graph=[[] for i in range(n)]
sirusi=[0]*n
for i in range(m):
    a,b=map(int,input().split())
    a-=1;b-=1
    graph[a].append(b)
    graph[b].append(a)
D=deque([0])
visited=[False]*n
visited[0]=True
depth = [0] * n
while D:
    v=D.popleft()
    for i in graph[v]:
        if visited[i]:continue
        visited[i]=True
        #sirusi[i]=v
        depth[i] = depth[v] + 1
        D.append(i)
print("Yes")
for i in range(1,n):
    print(depth[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    RoomNum,PathNum=map(int,input().split())

    G=[[] for _ in range(RoomNum)]

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

    dist=[-1]*RoomNum
    que=deque([])
    dist[0]=0
    que.append(0)

    sign=[]
    room_num=[]

    print(G)

    while len(que)>0:
        v=que.popleft()

        for i in G[v]: #vからつながっている頂点をすべて調べる
            if dist[i]!=-1: #すでに発見済み（キューに追加済み）は無視
                continue
            dist[i]=v #発見したら深さを更新するが今回は看板の数字
            que.append(i)

    if (-1 in dist): #未発見のものが残っているとき
        print("No")
    else:
        print("Yes")
        for i in dist[1:]:
            print(i+1)

if __name__=="__main__":
    main()

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[1]
for j in range(M-1):
    for visit in nextvisit[j]:
        for k in range(len(L)):
            erase = []
            if visit == L[k][1] and (L[k][0] not in visited):
                nextvisit[j+1].append(L[k][0])
                visited.append(L[k][1])
                visited.append(L[k][0])
                room[L[k][0]-1] = L[k][1]
                erase.append(k)
            if visit == L[k][0] and (L[k][1] not in visited):
                nextvisit[j+1].append(L[k][1])
                visited.append(L[k][0])
                visited.append(L[k][1])
                room[L[k][1]-1] = L[k][0]
                erase.append(k)
                
        for j in erase:
            del L[j]

print("Yes")
for k in range(1, N):
    print(room[k])

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
    RoomNum,PathNum=map(int,input().split())

    G=[[] for _ in range(RoomNum)]

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

    dist=[-1]*RoomNum
    que=deque([])
    dist[0]=0
    que.append(0)

    sign=[]
    room_num=[]

    print(G)

    while len(que)>0:
        v=que.popleft()

        for i in G[v]: #vからつながっている頂点をすべて調べる
            if dist[i]!=-1: #すでに発見済み（キューに追加済み）は無視
                continue
            dist[i]=v #発見したら深さを更新するが今回は看板の数字
            que.append(i)

    if (-1 in dist): #未発見のものが残っているとき
        print("No")
    else:
        print("yes")
        for i in dist[1:]:
            print(i+1)

if __name__=="__main__":
    main()

Submission status: Wrong Answer

Solution code:
import queue
n, m = map(int, input().split())
a = [0 for i in range(m)]
b = [0 for i in range(m)]
dic = {}
for i in range(1, n+1):
    dic[i] = []
for i in range(m):
    a[i], b[i] = map(int, input().split())
    dic[a[i]].append(b[i])
    dic[b[i]].append(a[i])
res = 0
INF = 100010
l = [0 for i in range(n+1)]
l[1] = 1
michi = [INF for i in range(n+1)] 
michi[1] = 0
p = [1]
shi = 1
while True:
    tmp = []
    for i in p:
        for j in dic[i]:
            if l[j] == 0:
                l[j] = 1
                tmp.append(j)
    if not tmp:
        break
    for i in tmp:
        michi[i] = shi
    p = tmp
    shi = p[0]
for i in range(2, n+1):
    print(michi[i])

Submission status: Wrong Answer

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

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

from collections import deque

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

Submission status: Wrong Answer

Solution code:
N , M = map(int, input().split())
room = [-1 for k in range(N)]
L = [[] for k in range(M)]
for k in range(M):
    L[k] = list(map(int, input().split()))
nextvisit =[[] for k in range(M)]
nextvisit[0].append(1)
visited =[1]
for j in range(M-1):
    for visit in nextvisit[j]:
        for k in range(M):
            if visit == L[k][1] and (L[k][0] not in visited):
                nextvisit[j+1].append(L[k][0])
                visited.append(L[k][1])
                visited.append(L[k][0])
                room[L[k][0]-1] = L[k][1]
            if visit == L[k][0] and (L[k][1] not in visited):
                nextvisit[j+1].append(L[k][1])
                visited.append(L[k][0])
                visited.append(L[k][1])
                room[L[k][1]-1] = L[k][0]
if -1 in room[1:N]:
    print("No")
else:
    print("Yes")
    for k in range(1, N):
        print(room[k])

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=map(int,input().split())
arr=[[] for n in range(N)]
que=deque([1])

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

dist=[-1]*N
dist[0]=0
arr2=[0]*(N-1)

print("Yes")
while que:
  c=que.popleft()
  for i in arr[c-1]:
    if dist[i-1]!=-1:
      continue
    
    dist[i-1]=0
    arr2[i-2]=c
    que.append(i)
    
print(arr)   
for i in arr2:
  print(i)

Submission status: Wrong Answer

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

e = [[] for _ in range(N)]
for i in range(M):
    a, b = map(int, input().split())
    e[a-1].append(b-1)
    e[b-1].append(a-1)
visited = [0]*N
visited[0] = 1
que = [0]
while que:
    x = que.pop()
    for i in e[x]:
        if visited[i] == 0:
            visited[i] = x+1
            que.append(i)

print("Yes")


print(*visited[1:], sep="\n")

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

def read():
    return sys.stdin.readline().rstrip()

def main():
    n, m = map(int, read().split())
    p = deque([])
    d1 = {}
    d2 = {}
    for i in range(m):
        a, b = map(int, read().split())
        if a == 1:
            d1[b] = 1
            d2[b] = 1
        elif b == 1:
            d1[a] = 1
            d2[a] = 1
        else:
            p.append((a, b))
    while p:
        pi = p.popleft()
        if pi[0] in d1 and pi[1] not in d1:
            d1[pi[1]] = pi[0]
            d2[pi[1]] = d2[pi[0]] + 1
        elif pi[1] in d1 and pi[0] not in d1:
            d1[pi[0]] = pi[1]
            d2[pi[0]] = d2[pi[1]] + 1
        elif pi[0] in d1 and pi[1] in d1:
            if d2[pi[0]] > d2[pi[1]] + 1:
                d1[pi[0]] = pi[1]
                d2[pi[0]] = d2[pi[1]] + 1
            elif d2[pi[1]] > d2[pi[0]] + 1:
                d1[pi[1]] = pi[0]
                d2[pi[1]] = d2[pi[0]] + 1
        else:
            p.append(pi)
    print("Yes")
    for i in range(2, n + 1):
        print(d1[i])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# D

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import breadth_first_order

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

row = []
col = []
for i in range(M):
    r, c = list(map(int, input().split()))
    row.append(c-1)
    col.append(r-1)

data = [1] * (M)

csr = csr_matrix((data, (row, col)), shape=(N, N))
_, proc = breadth_first_order(csr, 0, directed=False)

if -9999 in proc[1:]:
  print('No')
else:
	print('\n'.join((proc[1:]+1).astype('str')))

Submission status: Wrong Answer

Solution code:
import numpy as np

N, M = (int(x) for x in input().split())
ls_A = []
ls_B = []
for i in range(M):
    A_i, B_i = (int(x) for x in input().split())
    ls_A.append(A_i)
    ls_B.append(B_i)

arr_A = np.array(ls_A)
arr_B = np.array(ls_B)

num = 0
ls_rank = [[1]]
ls_rank_all = [1]
while sum(len(v) for v in ls_rank) < N:
    ls_append_all = []
    for i in ls_rank[num]:
        ls_append_temp = list(arr_B[np.where(arr_A==i)]) + list(arr_A[np.where(arr_B==i)])
        ls_append = [i for i in ls_append_temp if i not in ls_rank_all]
        ls_append_all = ls_append_all + ls_append
        ls_rank_all = ls_rank_all + ls_append
    ls_rank.append(ls_append_all)
    num+=1
    print(num)
    print(ls_rank)

print('Yes')
for i in range(2,N+1):
    ls_pass = list(arr_B[np.where(arr_A==i)]) + list(arr_A[np.where(arr_B==i)])
    for y, row in enumerate(ls_rank):
        if i in row:
            ls_rank_down = ls_rank[y-1]
        else:
            pass
    print(list(set(ls_pass) & set(ls_rank_down))[0])

Submission status: Wrong Answer

Solution code:
from sys import stdin
from heapq import heappush, heappop


class Dijkstra:
    def __init__(self, num_nodes):
        self.n = num_nodes
        self.adj_list = [[] for _ in range(self.n)]

    # Edge数分回すことを想定
    def add_edge(self, start, end, weight=1, undirected=False):
        self.adj_list[start].append((end, weight))
        if undirected:
            self.adj_list[end].append((start, weight))

    def distance(self, start):
        # 始点から各頂点までの最短距離を格納する
        self.dist = [float('inf') for _ in range(self.n)]
        # 最短経路における, その頂点の前の頂点のIDを格納する
        self.prev = [-1 for _ in range(self.n)]
        self.dist[start] = 0
        self.flag = [set() for _ in range(self.n)]
        # 各要素は，(頂点vのID, startからある頂点vまでの仮の距離)からなるタプル
        q = []
        heappush(q, (start, 0))
        while len(q) != 0:
            src, prov_cost = heappop(q)
            # プライオリティキューに格納されている最短距離が, 現在計算できている最短距離より大きければ，distの更新をする必要はない
            if self.dist[src] < prov_cost:
                continue
            # 他の頂点の探索
            for val in self.adj_list[src]:
                dest, cost = val
                if self.dist[dest] > self.dist[src] + cost:
                    self.dist[dest] = self.dist[src] + cost  # distの更新
                    heappush(q, (dest, self.dist[dest]))  # キューに新たな仮の距離の情報をpush
                    self.prev[dest] = src
                    self.flag[dest].add(src)
        return self.dist

    def shortest_path(self, goal):
        path = [goal]
        dest = goal
        # 終点から最短経路を逆順に辿る
        while self.prev[dest] != float('inf'):
            if self.prev[dest] == -1:
                break
            path.append(self.prev[dest])
            dest = self.prev[dest]
        return path[::-1]


def get_result(data):
    N, M = data[0]
    A = data[1:]
    solver = Dijkstra(N)
    for val in A:
        solver.add_edge(val[0]-1, val[1]-1, undirected=True)
    _ = solver.distance(0)
    # flag = [set() for _ in range(N)]
    # for i in range(1, N):
    #     dest = i
    #     while solver.prev[dest] != float('inf'):
    #         if solver.prev[dest] == -1:
    #             break
    #         flag[dest].add(solver.prev[dest])
    #         dest = solver.prev[dest]

    flag = solver.flag[1:]
    # print(flag)
    for val in flag:
        if len(val) == 0:
            print('No')
            return None

    print('Yes')
    for val in flag:
        print(list(val)[-1]+1)
    return None


if __name__ == '__main__':
    raw_data = [val.rstrip() for val in stdin.readlines()]
    data = [list(map(int, val.split(' '))) for val in raw_data]
    result = get_result(data)
    # print(result)

Submission status: Wrong Answer

Solution code:
#n cave
#m way

temp1 = input().split(" ")
n = int(temp1[0])
m = int(temp1[1])

cavelist = [
    {
        "caveId": i,
        "connected": set()
    }
    for i in range(1, n + 1)
]

#print(cavelist)

for i in range(m):
    temp = input().split(" ")

    cavelist[int(temp[0]) - 1]["connected"].add(int(temp[1]))
    cavelist[int(temp[1]) - 1]["connected"].add(int(temp[0]))

#print(cavelist)

out = {1}

goalpath = [0 for i in range(n - 1)]

for cave in cavelist:

    if cave["caveId"] in out:
        for c in cave["connected"]:
            out.add(c)

    for c in cave["connected"]:
        if c != 1:
            if c in out and goalpath[c - 2] == 0:
                goalpath[c - 2] = cave["caveId"]

if 0 in goalpath:
    print('No')
else:
    print('Yes')
    for p in goalpath:
        print(p)

Submission status: Wrong Answer

Solution code:
from collections import deque

n,m = map(int,input().split())
graph = [[] for i in range(n)]
mark = [0]*n

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

d = deque([0])
visited = [False]*n
visited[0] = True

while d:
    v = d.popleft()
    for i in graph[v]:
        if visited[i]:continue
        visited[i] = True
        mark[i] = v
        d.append(i)



print('Yes')

for i in mark:
    print(i+1)

Submission status: Wrong Answer

Solution code:
N,M=list(map(int,(input().split())))
sign=[]
for k in range(M):
  A,B=list(map(int,(input().split())))
  sign.append(sorted([A,B]))
len_goal=[[-1,-1] for k in range(N+1)]
len_goal[1][0]=1
len_goal[1][1]=1

sign=sorted(sign)

for room in sign:
  # 両方に深さが設定されている場合、深いほうの深さを浅い方+1にして、行き先を浅い方にする
  if(len_goal[room[0]][0]>len_goal[room[1]][0] and len_goal[room[1]][0]>=0):
    len_goal[room[0]][0]=len_goal[room[1]][0]+1
    len_goal[room[0]][1]=room[1]
  # 上に同じ
  elif(len_goal[room[1]][0]>len_goal[room[0]][0] and len_goal[room[0]][0]>=0):
    len_goal[room[1]][0]=len_goal[room[0]][0]+1
    len_goal[room[1]][1]=room[0]

  # 片方にのみ深さが設定されている場合、もう片方の深さを片方+1にして、行き先を片方にする
  elif(len_goal[room[0]][0]<0 and len_goal[room[1]][0]>=0):
    len_goal[room[0]][0]=len_goal[room[1]][0]+1
    len_goal[room[0]][1]=room[1]

  # 上に同じ
  elif(len_goal[room[0]][0]>=0 and len_goal[room[1]][0]<0):
    len_goal[room[1]][0]=len_goal[room[0]][0]+1
    len_goal[room[1]][1]=room[0]
  elif(len_goal[room[0]][0]==len_goal[room[1]][0]):
    pass
  else:
    print(1/0)


print("Yes")
for z in len_goal[2:]:
  print(z[1])