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

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

hist= []
visited_pos = [-1] * n

#初期情報
#print(ab)
ts = {}
for el in ab:
  wk = ts.get(el[0]) 
  if wk is None:
    sss  = set()
    ts[el[0]] = sss
  ts[el[0]].add(el[1])
  wk = ts.get(el[1]) 
  if wk is None:
    sss  = set()
    ts[el[1]] = sss
  ts[el[1]].add(el[0])
#print(ts)


#幅優先探索
def tsk(pos):
  wk = ts.get(pos)
  if ts.get(pos) is None:
    return
  else:
    #print(wk)
    for e in wk:
      if visited_pos[e-1] < 0:
        visited_pos[e-1] = pos
        hist.append(e)

idx = 1
hist.append(1)
while True:
  if idx > len(hist):
    break
  else:
    tsk(idx)
    idx += 1
#print(hist)
#print(visited_pos)
ans = 'Yes'
for i in range(n):
  if visited_pos[i] == -1:
    ans = 'No'
    break

print(ans)
if ans == 'Yes':
  for i in range(1,n):
    print(visited_pos[i])

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 ans.count(0) < 3:
                break

            if n in item:
                tmpl = copy.copy(item)

                tmpl.remove(n)

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

        else:
            continue
        break
    break

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:
import math
import sys

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

inputlist = []
for _ in range(n):
    inputlist.append([])

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

# 実装

ans = [-1] * n


def check(liin):
    for i in inputlist[liin]:
        if (ans[i - 1] == -1):
            ans[i - 1] = liin+1


for inputindex in range(n):
    for liin in inputlist[inputindex]:
        if (ans[liin-1] == -1):
            ans[liin - 1] = inputindex + 1
            check(liin-1)


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

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
c = [[] for _ in range(n)]
s = []
ans = [0]*n
for _ in range(m):
    a,b = map(int, input().split())
    c[a-1].append(b-1)
    c[b-1].append(a-1)
    if a == 1:
        s.append(b-1)
        ans[b-1] = 1
    elif b== 1:
        s.append(a-1)
        ans[a-1] = 1

for i in s:
    for j in c[i]:
        if not ans[j]:
            ans[j] = i+1

print('Yes')
for ans in ans[1:]:
    print(ans)

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)
ilist=[]

for i in range(M):
    if AB[i][0] == 1:
         sign[AB[i][1]-2] = 1
         ilist.append(i)
    elif AB[i][1] == 1:
         sign[AB[i][0]-2] = 1
         ilist.append(i)
for i in range(len(ilist)):
    del AB[ilist[i]-i]
ilist = []
length = len(AB)
#print(AB)

for i in range(length):
    if sign[AB[i][0]-2] == 1 and sign[AB[i][1]-2] != 1:
        sign[AB[i][1]-2] = AB[i][0]
        ilist.append(i)
    elif sign[AB[i][1]-2] == 1 and sign[AB[i][0]-2] != 1:
        sign[AB[i][0]-2] = AB[i][1]
        ilist.append(i)
for i in range(len(ilist)):
    del AB[ilist[i]-i]
ilist = []
length = len(AB)

for i in range(50):
    for i in range(length):
        if sign[AB[i][0]-2] != 0 and sign[AB[i][1]-2] == 0:
            sign[AB[i][1]-2] = AB[i][0]
            ilist.append(i)
        elif sign[AB[i][1]-2] != 0 and sign[AB[i][0]-2] == 0:
            sign[AB[i][0]-2] = AB[i][1]
            ilist.append(i)
    for i in range(len(ilist)):
#        print(ilist)
        del AB[ilist[i]-i]
#        print(AB)
    ilist = []
    if len(AB) == length:
        break
    else:
        length = len(AB)
#        print(length)

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

Submission status: Wrong Answer

Solution code:
n,m = map(int, input().split())
G = {i:[] for i in range(1, n+1)}

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

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

while check_list:
  n = check_list.pop()
  for g_i in G[n]:
    if ans[g_i]==-1:
      ans[g_i]=n
      check_list.append(g_i)

flg = 'Yes'
if -1 in ans:
  flg = 'No'

if flg=='Yes':
  print('Yes')
  for ans_i in ans[2:]:
    print(ans_i)
else:
  print('No')

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import os
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from io import BytesIO, IOBase
from typing import Dict, List, Optional, Set, Tuple


def solve(values: List[Tuple[int, int]], n: int) -> List[int]:
    passages = defaultdict(set)
    for a, b in values:
        passages[a].add(b)
        passages[b].add(a)
    if len(passages) < n:
        return []
    to_visit = deque((1,))
    visited = set()
    # 0 idx is not used
    distances = [n + 1] * (n + 1)
    distances[1] = 0
    signs = [1] * (n + 1)
    while to_visit:
        cur = to_visit.popleft()
        for neighbour in passages[cur]:
            tmp = distances[cur] + 1
            if tmp < distances[neighbour]:
                distances[neighbour] = tmp
                signs[neighbour] = cur
            if neighbour not in visited:
                to_visit.append(neighbour)
        visited.add(cur)
    # LOG.debug((visited))
    # LOG.debug((distances))
    if len(visited) < n:
        return []
    return signs[2:]


def do_job(stdin, stdout):
    "Do the work"
    LOG.debug("Start working")
    N, M = map(int, stdin.readline().split())
    if M < N:
        print("No", file=stdout)
        return
    values = []
    for _ in range(M):
        a, b = map(int, stdin.readline().split())
        values.append((a, b))
    result = solve(values, N)
    if not result:
        print("No", file=stdout)
    else:
        print("Yes", file=stdout)
        print("\n".join(map(str, result)), file=stdout)


def print_output(testcase: int, result, stdout) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result), file=stdout)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result), file=stdout)


BUFSIZE = 8192


class FastIO(IOBase):
    # pylint: disable=super-init-not-called, expression-not-assigned
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    # pylint: disable=super-init-not-called
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(IOWrapper(sys.stderr))
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    stdin = IOWrapper(sys.stdin)
    stdout = IOWrapper(sys.stdout)
    do_job(stdin, stdout)
    stdout.flush()
    for h in LOG.handlers:
        h.flush()
    return 0


if __name__ == "__main__":
    sys.exit(main())

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]

n, m = map(int,input().split())
g =Graph()
for _ in range(m):
    x, y = map(int,input().split())
    g.add_edge(x-1,y-1,1)
    g.add_edge(y-1,x-1,1)
d = Dijkstra(g,0)

ans= [float("inf") for i in range(n)]
for i in range(n):
    x = d.shortest_distance(i)
    ans[i] = x
if float("inf") in ans:
    print('No')
else:
    print('Yes')
    for i in range(1,n):
        print(ans[i])

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
import numpy as np
# D

N, M = list(map(int, input().split()))
ABs = np.array([list(map(int, input().split())) for i in range(M)])

row = list(ABs.T[0]-1) + list(ABs.T[1]-1)
col = list(ABs.T[1]-1) + list(ABs.T[0]-1)
data = [1] * (2 * M)

csr = csr_matrix((data, (row, col)), shape=(N, N))
from_starts, procs = dijkstra(csr, indices=[0], return_predecessors=True)
proc = procs[0]+1
 
if -9999 in proc[1:]:
  print('No')
else:
  print('Yes')
  print('\n'.join(proc[1:].astype('str')))

Submission status: Wrong Answer

Solution code:
import math

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

r = [0]*(n-1)

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

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

node_num = len(route_list) 

unsearched_nodes = list(range(node_num)) 
distance = [math.inf] * node_num 
previous_nodes = [-1] * node_num 
distance[0] = 0 

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

while(len(unsearched_nodes) != 0): 
    posible_min_distance = math.inf 
    for node_index in unsearched_nodes: 
        if posible_min_distance > distance[node_index]: 
            posible_min_distance = distance[node_index] 
    target_min_index = get_target_min_index(posible_min_distance, distance, unsearched_nodes) 
    unsearched_nodes.remove(target_min_index)

    target_edge = route_list[target_min_index] 
    for index, route_dis in enumerate(target_edge):
        if route_dis != 0:
            if distance[index] > (distance[ target_min_index] + route_dis):
                distance[index] = distance[ target_min_index] + route_dis 
                previous_nodes[index] =  target_min_index 


previous_node = node_num - 1
print("Yes")
while previous_node != -1:
    if previous_node !=0:
        print(str(previous_node + 1))
    else:
        print(str(previous_node + 1))
    previous_node = previous_nodes[previous_node]

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split(" "))
l = []
an = [1] + [0 for n in range(1,n)]
turo = []
for i in range(m):
    l = list(map(int, input().split()))
    turo.append(l)
count = 0
num = 1
while count < n-2:
    for a,num in enumerate(an):
        if num != 0:
            for l in turo:   
                for i,x in enumerate(l):
                    if x == a+1:
                        if an[l[(i+1)%2]-1] == 0:
                            an[l[(i+1)%2]-1] = a+1
                            count += 1
flag = 0
for i in an:
    if i == 0:
        flag+=1
if flag == 0:
    print("Yes")        
    for i in range(1,len(an)):
        print(an[i])
else:
    print("No")

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)

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

    while d:
        # print(d, ans)
        node, l = d.popleft()

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

        # if -1 not in set(ans): TLEなる
        #     break

    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:
n, m = list(map(int, input().split()))

links = []

for i in range(m):
    a, b = list(map(int, input().split()))
    links.append(sorted([a, b]))

set = (links)


def search(s, i):
    if i == 1:
        return 1
    ways = []
    sets = []
    for j in s:
        if i in j:
        # if j[1] == i:
            if j[0] == i:
                ways.append(j[1])
                sets.append(j)
            else:
                ways.append(j[0])
                sets.append(j)
    if len(ways) > 0:
        index = ways.index(min(ways))
        s.remove(sets[index])
        return search(s, ways[index])
    return 0


for i in range(2,n+1):
    s = set.copy()
    if search(s, i) == 0:
        print('No')
        exit()
print('Yes')
for i in range(2,n+1):
    ways = []
    sets = []
    ss = set.copy()
    for s in ss:
        if i in s:
            if s[0] == i:
                ways.append(s[1])
                sets.append(s)
            else:
                ways.append(s[0])
                sets.append(s)
    if len(ways) > 0:
        index = ways.index(min(ways))
        ss.remove(sets[index])
        print(ways[index])

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
a=[0]*m
b=[0]*m
c=[0]*n
f=0
flag=0
for i in range(m):
    a[i],b[i]=map(int,input().split())
    if a[i]==1:
        c[b[i]-1]=1
        f=f*10+b[i]
        flag+=1
    elif b[i]==1:
        c[a[i]-1]=1
        f=f*10+a[i]
        flag+=1
p=list(map((lambda x: int(x)), list(str(f))))
print(p)
for j in range(len(p)):
    for i in range(m):
        if p[j]==a[i]:
            if c[b[i]-1]==0:
                c[b[i]-1]=a[i]
                flag+=1
                for k in range(len(p)):
                    if p[j]==b[i]:
                        break
                    if k==len(p)-1:
                        p.append(b[i])
        elif p[j]==b[i]:
            if c[a[i]-1]==0:
                c[a[i]-1]=b[i]
                flag+=1
                for k in range(len(p)):
                    if p[j]==a[i]:
                        break
                    if k==len(p)-1:
                        p.append(a[i])
if flag<n-1:
    print('No')
    exit()
print('Yes')
for i in range(1,len(c)):
    print(c[i])

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
d = deque()
d2 = deque()
As = [0] * m
Bs = [0] * m
Cs = [0] * (n + 1)  # 標

for i in range(m):
    a, b = map(int, input().split())
    As[i] = a
    Bs[i] = b


def solver(i, c):
    aindexs = [j for j, x in enumerate(As) if x == i]
    bindexs = [j for j, x in enumerate(Bs) if x == i]
    indexs = aindexs + bindexs
    for aindex in aindexs:
        d.append(Bs[aindex])
        d2.append(c + 1)
        Cs[Bs[aindex]] = c
    for bindex in bindexs:
        d.append(As[bindex])
        d2.append(c + 1)
        Cs[As[bindex]] = c
    for index in indexs:
        As[index] = -1
        Bs[index] = -1


solver(1, 1)
d.append(1)
d2.append(1)
while d:
    solver(d.popleft(), d2.popleft())

for i in range(2, n+1):
    if (Cs[i] == 0):
        print('No')
        exit()
print('Yes')
for i in range(2, n+1):
    print(Cs[i])

Submission status: Wrong Answer

Solution code:
def main():
    n,m = map(int,input().split())
    ab = []
    cnt = [0] * n
    road = [[] for i in range(n)]

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

    dist = [10**7] * n
    dist[0] = 0
    ans = [0] * n
    cnt = 0
    while True:
        for i, aa in enumerate(road):
            for j, t in enumerate(aa):
                if dist[i] > dist[t]+1:
                    dist[i] = dist[t]+1
                    ans[i] = t + 1
                    flg = True


        cnt += 1
        if cnt == 100:
            break
        if flg :
            flg = False
            continue
        else:
            break

    f = 'Yes'
    for i in range(n):
        if dist[i] == 10**7:
            f = 'No'
            break
        else:
            continue
    print(f)
    for i in range(1,n):
        print(ans[i])


if __name__=='__main__':
    main()

Submission status: Wrong Answer

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

import networkx as nx

YES = "Yes"  # type: str
NO = "No"


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    G = nx.Graph()
    G.add_nodes_from([1+n for n in range(N)])

    G.add_edges_from([(a,b) for a,b in zip(A,B)])

    paths = nx.predecessor(G, 1, cutoff=N-N//10)

    print(YES)

    ans_list = []
    for key, val in sorted(paths.items()):
        if key != 1:
            print(val[0])
            # ans_list.append((key,val[0]))

    # ans_list.sort(key=lambda x: x[0])
    # for key, val in ans_list:
    #     print(val)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
r = [list(map(int,input().split())) for i in range(m)]
inf = 9999999
la = [[] for i in range(n + 1)]
for i,j in r:
    la[i].append(j)
    la[j].append(i)

p = [0 for i in range(n+1)]
ex = [inf for i in range(n+1)]
do = []
ex[1] = 1

do.append(1)

while(len(do) != 0):
    x = do.pop(0)
    
    for i in la[x]:
        if ex[i] == 0 :
            do.append(i)
            ex[i] = ex[x]+1
            p[i] = x

if ex.count(inf) > 1:
    print("No")
    exit()
    
print("Yes")
for i in range(2,n+1):
    print(p[i])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
a_b = [[] for _ in range(M)]
A = [0]*M
B = [0]*M
for i in range(M):
    a_b[i] = list(map(int, input().split()))
    A[i] = a_b[i][0]
    B[i] = a_b[i][1]


ans = [-1] * N
ans[0] = 0
check = []
check.append(1)
memo = []

while True:
    memo = []
    for num in check:
        if num in A:
            list_a = [i for i, x in enumerate(A) if x == num]
            for index_a in list_a:
                if ans[B[index_a]-1] == -1:
                    ans[B[index_a]-1] = num
                    memo.append(B[index_a])
            list_b = [i for i, x in enumerate(B) if x == num]
            for index_b in list_b:
                if ans[A[index_b]-1] == -1:
                    ans[A[index_b]-1] = num
                    memo.append(A[index_b])
    if len(memo) == 0:
        break
    check = memo

if -1 in ans:
    print("No")
else:
    print("Yes")
    for j in ans[1:]:
        print(j)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
n, m = map(int, input().split())
G = [[] for _ in range(n)]
for _ in range(m):
    s,t = map(int, input().split())
    G[s-1].append((1, t-1))
    G[t-1].append((1, s-1))
    # G[t].append((d, s))

dist = [float('inf') for _ in range(n)]

prev = [(0,0)]

while len(prev):
    now = heappop(prev)
    if dist[now[1]] < now[0]:
        continue
    else:
        dist[now[1]] = now[0]
    for nxt in G[now[1]]:
        if dist[nxt[1]] > dist[now[1]] + nxt[0]:
            dist[nxt[1]] = dist[now[1]] + nxt[0]
            heappush(prev,(nxt[0]+dist[now[1]], nxt[1]))
    # print(now,prev,dist)
if max(dist) == float('inf'):
    print("No")
else:
    print("Yes")
    for i in range(1, n):
        print(dist[i])

Submission status: Wrong Answer

Solution code:
import numpy as np
from collections import deque

n, m = map(int, input().split())
ab = np.zeros([m, 2], dtype=int)
for i in range(m):
    a, b = map(int, input().split())
    ab[i] = [a,b]

nodes = [None]*n

for i in range(n):
    t = []
    for j1 in np.where(ab[:,0]==i+1)[0]:
        t.append(ab[j1,1]-1)
    for j2 in np.where(ab[:,1]==i+1)[0]:
        t.append(ab[j2,0]-1)
    nodes[i] = t

mins = np.zeros([n], dtype=int)
used = np.zeros_like(mins)
used[0] = 1
mins[:] = -1
q = deque()
q.append(0)
step = 0
while not len(q)==0:
    v = q.pop()
    for i in nodes[v]:
        if not used[i]:
            used[i] = 1
            mins[i] = v
            q.append(i)

if all(mins[1:] >= 0):
    print('Yes')
    for i in range(1,n):
        print(mins[i]+1)
else:
    print('No')

Submission status: Wrong Answer

Solution code:

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

searched = []
candidates = []
ans = [0 for __ in range(n+1)]

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


candidates.append(1) # start position

while True:
    if len(candidates) != 0:
        x = candidates.pop(-1)
        searched.append(x)
        y = searched[-1]
        for i in range(len(pic[y])):
            if pic[y][i] not in searched and pic[y][i] not in candidates:
                candidates.append(pic[y][i])
            if ans[pic[y][i]] == 0:
                ans[pic[y][i]] = y
    else:
        break

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

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix

from scipy.sparse.csgraph import dijkstra

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

edge = np.array([input().split() for _ in range(M)], dtype = np.int64).T

graph = csr_matrix(([1]*M, (edge - 1)), (N, N))


distance_mat, processors = dijkstra(graph, directed = False, indices = [0, 1], return_predecessors = True)


for i in range(1,len(processors[0])):
    print(processors[0][i]+1)

Submission status: Wrong Answer

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

N ,M = map(int, input().split())
edge = np.array([input().split() for _ in range(M)], dtype = np.int64).T
a = np.ones((1,M))
edge = np.vstack([edge,a])

graph = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))

distance_mat, processors = dijkstra(graph, directed = False, indices = 0, return_predecessors = True)

print("Yes")
processors = list(processors)
[print(i+1) for i in processors[1:]]

Submission status: Wrong Answer

Solution code:
N, M = 6, 9
ARR = [
    [3, 4],
    [6, 1],
    [2, 4],
    [5, 3],
    [4, 6],
    [1, 5],
    [6, 2],
    [4, 5],
    [5, 6],
]

N,M = 4, 4
ARR = [
    [1, 2],
    [2, 3],
    [3, 4],
    [4, 2],
]


import sys

sys.setrecursionlimit(1000000)


N, M = map(int, input().split())
ARR = []

for i in range(M):
    ARR.append(list(map(int, input().split())))


def prepare(n, m, arr):
    nodes = [[] for i in range(n)]
    nodeStates = [False for i in range(n)]
    nodeResults = [0 for i in range(n - 1)]
    nodeCount = [0 for i in range(n)]
    nodedistance = [-1 for i in range(n)]
    for i in range(m):
        startNode = arr[i][0] - 1
        endNode = arr[i][1] - 1

        nodes[startNode].append(endNode)
        nodes[endNode].append(startNode)

    return nodes, nodeStates, nodeResults, nodeCount, nodedistance


nodes, nodeStates, nodeResults, nodeCount, nodedistance = prepare(N, M, ARR)

def dfs(currentNode, parentNode, nodes, distance):
    childrenNodes = nodes[currentNode]

    if nodeCount[currentNode] == len(nodes[currentNode]):
        return

    if currentNode >= 1:
        if nodedistance[currentNode] == -1:
            nodedistance[currentNode] = distance
            nodeResults[currentNode - 1] = parentNode + 1
        else:
            if distance < nodedistance[currentNode]:
                nodedistance[currentNode] = distance
                nodeResults[currentNode - 1] = parentNode + 1

    nodeStates[currentNode] = True
    nodeCount[currentNode] = nodeCount[currentNode] + 1
    nodedistance[currentNode] = distance
    for childNode in childrenNodes:
        dfs(childNode, currentNode, nodes, distance + 1)


dfs(0, -1, nodes, 0)

if sum(nodeStates) == N:
    print("Yes")
    for i in range(N - 1):
        print(nodeResults[i])
else:
    print("No")

Submission status: Wrong Answer

Solution code:

N, M = map(int, input().split())
AB = [list(map(int, input().split())) for i in range(M)]
R = [0] * N
P = 0
S = [1]
Stmp = []
while True:
    for i in range(M):
        for s in S:
            if AB[i][0] == s:
                R[AB[i][1] - 1] = s
                Stmp.append(AB[i][1])
                AB[i] = [0, 0]
                P += 1
            elif AB[i][1] == s:
                R[AB[i][0] - 1] = s
                Stmp.append(AB[i][0])
                AB[i] = [0, 0]
                P += 1
    S = Stmp
    Stmp = []
    if P >= N - 1:
        break
print('Yes')
for i in range(1, N):
    print(R[i])