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: Time Limit Exceeded

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 - 1:
        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: Time Limit Exceeded

Solution code:
import numpy as np

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

sign=np.array([0]*(N-1))

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

for k in range(N-1):
    for i in range(N-1):
        temp_sign=sign
        if sign[i] != 0:
            for j in range(M):
                if A[j]==(i+2) and sign[B[j]-2]==0:
                    temp_sign[B[j]-2]=(i+2)
                elif B[j]==(i+2) and sign[A[j]-2]==0:
                    temp_sign[A[j]-2]=(i+2)
        sign=temp_sign
    if all(sign!=0):
        break

if all(sign!=0):
    print('Yes')
    for i in sign:
        print(i)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


input = sys.stdin.readline


def torf():
    for i in range(2, N):
        n = B[i-2]
        count = 1
        while n != 1:
            n = B[n-2]
            count += 1
        if count != D[i-1]:
            return False
    return True


def main():
    while que:
        nn = que.popleft()
        for n in edges[nn-1]:
            if D[n-1] == INF or D[n-1] > D[nn-1] + 1:
                D[n-1] = D[nn-1] + 1
                que.append(n)
                if n > 1:
                    B[n-2] = nn
    if torf():
        print("Yes")
        for b in B:
            print(b)
    else:
        print("No")


if __name__ == "__main__":
    N, M = map(int, input().split())
    edges = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        edges[a-1].append(b)
        edges[b-1].append(a)
    B = [0]*(N-1)
    que = deque([1])
    INF = 10**10
    D = [INF]*N
    D[0] = 0
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, defaultdict


def bfs(graph, start):
    ans = 'Yes'
    ans_list = {}

    queue = deque([start])
    visited = set()
    distance = defaultdict(int)
    distance[start] = 0
    while queue:
        current_vertex = queue.popleft()
        visited.add(current_vertex)
        for v in graph[current_vertex]:
            if v not in visited and v not in queue:
                queue.append(v)
                distance[v] = distance[current_vertex] + 1
                if distance[v] == distance[current_vertex] + 1:
                    ans_list[v] = current_vertex
    return ans_list

N, M = map(int, input().split())
paths = [tuple(map(int, input().split())) for _ in range(M)]

graph = defaultdict(set)
for A, B in paths:
    graph[A].add(B)
    graph[B].add(A)

ans_list = bfs(graph, 1)
ans_list = sorted(ans_list.items())

if len(ans_list) != N-1:
    print('No')
else:
    print('Yes')
    for k, v in ans_list:
        print(v)

Submission status: Time Limit Exceeded

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

print("Yes")
print_start = 2
queue = [(e, 1) for e in edge[1]]
while len(queue) > 0:
    # print(queue)
    e, now = queue.pop(0)
    if reached[e] == 0:
        reached[e] = 1
        guide[e] = now
        if e == print_start:
            print(now)
            print_start += 1
        # edge[e].remove(now)
        for next in edge[e]:
            if next != 1 and reached[next] == 0:
                queue.append((next, e))

for i in range(print_start, n+1):
    print(guide[i])

Submission status: Time Limit Exceeded

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

Vector = [0]*(N+1)
q = []

for i in range (0, M):
	if P[i][0] == 1:
		Vector[P[i][1]] = 1
		q.append(P[i][1])

while q:
	value = q.pop(0)
	for i in range (0,M):
		if P[i][0] == value and Vector[P[i][1]]==0:
			q.append(P[i][1])
			Vector[P[i][1]] = value
		if P[i][1] == value and Vector[P[i][0]]==0:
			q.append(P[i][0])
			Vector[P[i][0]] = value

print('Yes')
print(*Vector[2::])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


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

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

ab_count = {key:[] for key in range(1,n+1)}

for i in range(m):
    ab_count[ab_list[i][0]].append(ab_list[i][1])
    ab_count[ab_list[i][1]].append(ab_list[i][0])


#print(ab_count)

que = deque()

#始点は1、階層は0からスタート
que.append([1,0])

checked_dict = {key:[] for key in range(1,n+1)}
temp_dict = {key:[] for key in range(1,n+1)}
where = 0

while que:
    x_pop = que.popleft()
    x = x_pop[0]
    if where != x_pop[1]:
        #階層が代わったから、temp_dictをchecked_dictへ反映させる処理
        for k in range(1,n+1):
            if len(checked_dict[k]) == 0:
                checked_dict[k] = temp_dict[k]
            else:
                aaa = set(checked_dict[k]) & set(temp_dict[k])
                if aaa != set():
                    checked_dict[k] = list(aaa)

    where = x_pop[1]

    for j in ab_count[x]:
        if len(checked_dict[j]) == 0:
            #OK,temp_dictに入れて、queに入れる。
            temp_dict[j].append(x)
            que.append([j,where+1])
        else:
            continue

    

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N,M=(int(x) for x in input().rstrip('\n').split())
road=[]
for i in range(1,M+1):
  road.append([int(x) for x in input().rstrip('\n').split()])
now=[1]
used = {}
for i in range(1,M+1):
  nex = [x for x in road if any(y in x for y in now)]
  for x in nex:
    used.setdefault(x[1],x[0])
    used.setdefault(x[0],x[1])
    now.extend(x)
print('Yes')
for i in range(2,N+1):
  print(used[i])

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline

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

    # newAB = [0]*(2*M)
    # for i, ab in enumerate(AB):
    #     newAB[2*i] = ab
    #     newAB[2*i + 1] = ab[::-1]
    # newAB = sorted(newAB, key=lambda x: x[0])
    # print(newAB)

    # visited = set([1])
    # before = [0]*(N-1)
    # dist = [0]*(N-1)

    # for a,b in newAB:
    #     if len(visited) == N
    #     if b in visited:
    #         continue

# ###
    from collections import deque
    search = deque([1])
    visited = set([])
    before = [0] * (N-1)
    while search:
        s = search.popleft()
        visited.add(s)
        for a, b in AB:
            if s == a:
                new_s = b
            elif s == b:
                new_s = a
            else:
                continue
            if new_s in visited:
                continue
            if new_s in set(search):
                continue

            search.append(new_s)
            before[new_s-2] = s
    if 0 in before:
        print('No')
    else:
        print('Yes')
        for b in before:
            print(b)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split( ))
all_ = set([i for i in range(1,N)])
child = [[] for _ in range(N)]
ans = [[] for _ in range(N)]
for _ in range(M):
    ab = list(map(int,input().split( )))
    child[ab[0]-1].append(ab[1]-1)
    child[ab[1]-1].append(ab[0]-1)
child = list(map(set,child))
check = [0]
while len(all_ ) != 0:
    checkk = {-1}
    for c in check:
        a = child[c] & all_
        ans[c] = list(a)
        checkk = checkk | set(a)
        all_ = all_ - child[c]
    check = checkk - {-1}
anss = [[] for i in range(N)]
for i in range(N):
    for a in ans[i]:
        anss[a] = i
print('Yes')
for a in anss[1:]:
    print(a + 1)

Submission status: Time Limit Exceeded

Solution code:


roomNum, rootNum = map(int, input().split())


rootArray = []
for _ in range(rootNum):
    rootArray.append(list(map(int, input().split())))

result = [0] * roomNum

target = 1
while result.count(0) != 0:
    print(result)
    for tmp in range(rootNum):
        if rootArray[tmp][0] == target and rootArray[tmp][1] >= target :
            result[target - 1] = target
            target = rootArray[tmp][1]
            break
        if rootArray[tmp][1] == target and rootArray[tmp][0] >= target :
            result[target - 1] = target
            target = rootArray[tmp][0]
            break

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n, m = map(int, input().split())
a = [0] * m
b = [0] * m
for i in range(m):
    aa, bb = map(int, input().split())
    a[i], b[i] = aa, bb

path = [[] for _ in range(n+1)]
for i in range(m):
    aa, bb = a[i], b[i]
    path[bb].append(aa)
    path[aa].append(bb)

ans = [0] * (n+1)
que = deque([[1, 1]])
while len(que) > 0:
    idx = que.popleft()
    if ans[idx[0]] == 0:
        ans[idx[0]] = idx[1]
    for i in path[idx[0]]:
        if ans[i] == 0:
            deque.append(que, [i, idx[0]])

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

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
cost = [[float("inf") for i in range(N)] for i in range(N)]
for i in range(M):
  A, B = map(int, input().split())
  cost[A-1][B-1] = 1
  cost[B-1][A-1] = 1

def dijkstra(s, n, cost):
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    pre = [-1 for i in range(n)]
    
    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):
              if d[j] > d[v] + cost[v][j]:
                d[j] = d[v] + cost[v][j]
                pre[j] = v
    return d, pre

d, pre = dijkstra(0, N, cost)
print("Yes")
for v in pre[1:]:
  print(v+1)

Submission status: Time Limit Exceeded

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

print("Yes")


ans = [0] * (N-1)
flag = [0] * len(a)
current = [1]
next_room = []

while ans.count(0) != 0:
    for c in range(len(current)):
        for m in range(len(a)):
            if current[c] in a[m]:
                if a[m][0] == current[c]:
                    if ans[a[m][1]-2] == 0:
                        ans[a[m][1]-2] = current[c]
                        next_room.append(a[m][1])
                        flag[m] = 1

                else:
                    if ans[a[m][0]-2] == 0:
                        ans[a[m][0]-2] = current[c]
                        next_room.append(a[m][0])
                        flag[m] = 1
    for k in range(len(a)-1,0,-1):
      if flag[k] ==1:
        del a[k]
    current = list(set(next_room))
[print(x) for x in ans]

Submission status: Time Limit Exceeded

Solution code:
import queue

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

a, b = [], []
result = [-1] * n
way = dict()
result[0] = 0

for i in range(m):
    aa, bb = map(int, input().split())

    way[aa - 1] = way.get(aa - 1, []) + [bb - 1]
    way[bb - 1] = way.get(bb - 1, []) + [aa - 1]

waits = queue.Queue()
waits.put(0)


while not waits.empty():
    current = waits.get()

    for w in way.get(current, []):
        if result[w] == -1:
            result[w] = current + 1
            waits.put(w)

if -1 in result:
    print("No")
else:
    print("Yes")
    for i in result[1:]:
        print(i)

Submission status: Time Limit Exceeded

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

inv = [i for i in range(N-1)]
visited = [1]

path = [[] for i in range(N)]

for i in range(M):
  A, B = map(int, input().split())
  path[A-1].append(B)
  path[B-1].append(A)
nows = [1]
for t in range(N):
  buf = []
  buf2 = []
  for now in nows:
    buf2 = buf2 + path[now-1]
  buf2 = set(buf2)
  buf3 = set(visited)
  buf2 = buf2 - buf3
  for p in buf2:
    buf.append(p)
    visited.append(p)
    inv[p-2]=now
  if len(buf2)==0:
    break
  nows = buf
print("Yes")
for i in inv:
  print(i)

Submission status: Time Limit Exceeded

Solution code:

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

p = [[] for _ in range(n+1)]
f = [0] * (n + 1)
x = [0] * (n + 1)

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

st = [1]

while (len(st) > 0):
    ls = len(st)
    for i in st[:]:
        for j in p[i]:
            if(f[j] == 0):
                st += [j]
                f[j] = i
    st = st[ls:]

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

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
A, B = [], []
for i in range(M):
    a, b = map(int, input().split())
    A.append(a)
    B.append(b)

class Rs():
    def __init__(self):
        self.Rs = []

    def append(self, R):
        self.Rs.append(R)

    def search(self):
        count = 1
        new_nodes, count = self._search(1, count)
        while count < N:
            _new_nodes = set()
            for num in new_nodes:
                _new_node, count = self._search(num, count)
                _new_nodes.update(_new_node)
            new_nodes = _new_nodes

        return [ self.Rs[i].fastest_room for i in range(1,len(self.Rs)) ]

    def _search(self, num, count):
        r = self.Rs[num-1]
        cons = r.connection
        new_nodes = set()
        cons -= r.searched_from

        for con in cons:
            if len(self.Rs[con-1].searched_from) == 0:
                self.Rs[con-1].fastest_room = num
                self.Rs[con-1].searched_from.add(num)
                new_nodes.add(con)
                count += 1
            else:
                continue
        return new_nodes, count

class R():
    def __init__(self, num, connection):
        self.num        = num
        self.connection = connection
        self.searched_from = set([])
        self.fastest_room = None

r = Rs()
for i in range(N):
    cons = []
    for j, (a, b) in enumerate(zip(A, B)):
        if a == (i+1):
            cons.append(B[j])
        elif b == (i+1):
            cons.append(A[j])
    r.append(R(i+1, set(cons)))

l = r.search()
print("Yes")
for room in l:
    print(room)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline

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

    newAB = [0]*(2*M)
    for i, ab in enumerate(AB):
        newAB[2*i] = ab
        newAB[2*i + 1] = ab[::-1]
    newAB = sorted(newAB, key=lambda x: x[0])
    # print(newAB)

    # visited = set([1])
    # before = [0]*(N-1)
    # dist = [0]*(N-1)

    # for a,b in newAB:
    #     if len(visited) == N
    #     if b in visited:
    #         continue

# ###
    from collections import deque
    search = deque([1])
    visited = set([])
    before = [0] * (N-1)
    while search:
        s = search.popleft()
        visited.add(s)
        for a, b in AB:
            if s == a:
                new_s = b
            elif s == b:
                new_s = a
            else:
                continue
            if new_s in visited:
                continue
            if new_s in set(search):
                continue

            search.append(new_s)
            before[new_s-2] = s
    if 0 in before:
        print('No')
    else:
        print('Yes')
        for b in before:
            print(b)
###
    # from scipy.sparse import csgraph, csr_matrix
    # import numpy as np

    # start = [0] * M
    # end = [0] * M
    # cost = [1]*M
    # for i in range(M):
    #     start[i] = AB[i][0]-1
    #     end[i] = AB[i][1]-1
    # csr = csr_matrix((cost, (start, end)), shape=(N, N))

    # d, p = csgraph.dijkstra(csr, return_predecessors=True,
    #                         indices=[0], directed=False)
    # if np.any(d == np.inf):
    #     print('No')
    # else:
    #     print('Yes')
    #     for i in range(1, N):
    #         print(get_path(0, i, p)[-2]+1)


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]


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline 
sys.setrecursionlimit(10 ** 6)

def main():
  N,M = map(int,input().split())
  path = [[] for i in range(N)]
  inf = 10 ** 6 * 2
  
  ans = [[None,inf] for i in range(N - 1)]
  
  for _ in range(M):
    a,b = map(int,input().split())
    a = a - 1
    b = b - 1
    path[a].append(b)
    path[b].append(a)
  
  def dfs(cur,par,con):
    if con == N + 1:
      return
    for chi in path[cur]:
      if chi == par:
        continue
      if con < ans[chi - 1][1]:
        ans[chi - 1][0] = cur
        ans[chi - 1][1] = con + 1
        dfs(chi,cur,con + 1)
  
  dfs(0,-1,0)
  
  if all([i[0] != None for i in ans]):
    print("Yes")
    for i in range(N - 1):
      print(ans[i][0] + 1)
  else:
    print("No")

if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N, M = map(int, input().split())
p = [0]
ans = [0]
D = deque()
for i in range(N):
    p.append(list())
    if i == 0:
        ans.append(0)
    else:
        ans.append(-1)
for i in range(M):
    A, B = map(int, input().split())
    p[A].append(B)
    p[B].append(A)
D.append(1)
while len(D) != 0:
    ind = D.popleft()
    for i in p[ind]:
        if ans[i] == -1:
            D.append(i)
            ans[i] = ind
    if -1 not in ans[2:]:
        break
if -1 in ans[2:]:
    print('No')
else:
    print('Yes')
    for i in ans[2:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict, deque
input = sys.stdin.readline
N, M = map(int, input().split())
guidepost = [None] * N
distance = [0] + [10**9] * (N - 1)
dd = defaultdict(list)
for _ in range(M):
    a, b = map(int, input().split())
    dd[a].append(b)
    dd[b].append(a)
stack = deque([1])
checked = [False] * N
while len(stack) >= 1:
    i = stack.popleft()
    checked[i - 1] = True
    for j in dd[i]:
        distance[j - 1] = min(distance[j - 1], distance[i - 1] + 1)
        if guidepost[j - 1] is None:
            guidepost[j - 1] = i
        elif distance[guidepost[j - 1] - 1] > distance[i - 1]:
            guidepost[j - 1] = i
        if not checked[j - 1]:
            stack.append(j)
print('Yes')
for i in range(1, N):
    print(guidepost[i])

Submission status: Time Limit Exceeded

Solution code:
line1 = input().split()
n = int(line1[0])
m = int(line1[1])

road_map = [[] for i in range(n)]

for i in range(m):
  line = input().split()
  a = int(line[0]) - 1
  b = int(line[1]) - 1
  road_map[a].append(b)
  road_map[b].append(a)

current_goal = [0]
route = [-1] * n
route[0] = 0
none = True
while none:
  goal = current_goal
  current_goal = []
  none = False
  for i in range(n):
    road = road_map[i]
    if route[i] >= 0:
      continue
    dist = -1
    for r in road:
      if r in goal:
        dist = r
    if dist >= 0:
      current_goal.append(i)
      route[i] = dist
      none = True
if min(route) == -1:
  print("No")
else:
  print("Yes")
  for ro in route[1:n]:
    print(ro + 1)

Submission status: Time Limit Exceeded

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


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



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



def adv(r,x,y):
    global visited
    if y > n:
        return
    else:
        yy = y + 1
        last_room = x
        if michishirube[x][1] > yy:
            michishirube[x][0] = r
            michishirube[x][1] = yy
            for i in tsuro[x]:
                if i == 0:
                    pass
                else:
                    adv(last_room,i,yy)
        else:
            return

for i in tsuro[0]:
    adv(0,i,0)



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

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
A = [0 for i in range(M)]
B = [0 for i in range(M)]
KOTAE = [0 for i in range(N)]
KOTAE[0] = 'Yes'
HOZON = [1]
HOZON2 = []
HOZON3 = []
for i in range(M):
    A[i],B[i] = map(int,input().split())
S = 0
for j in range(M):
    for i in range(M):
        if A[i] in HOZON and not(A[i] in HOZON2  or A[i] in HOZON3 or B[i] in HOZON or B[i] in HOZON2 or B[i] in HOZON3):
            HOZON2.append(B[i])
            KOTAE[B[i]-1] = A[i]
        elif B[i] in HOZON and not(A[i] in HOZON or A[i] in HOZON2  or A[i] in HOZON3 or B[i] in HOZON2 or B[i] in HOZON3):
            HOZON2.append(A[i])
            KOTAE[A[i]-1] = B[i]
    HOZON3.extend(HOZON)
    HOZON = HOZON2
    HOZON2 = []
    if len(HOZON3) == N:
        break
for i in range(N):
    print(KOTAE[i])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
l = [list(map(int, input().split())) for i in range(m)]
d = [0] + [100000]*(n-1)
a = [[float('inf') for j in range(n)] for i in range(n)]
t = [0]*n

for i in range(m):
    a[l[i][0]-1][l[i][1]-1] = 1
    a[l[i][1]-1][l[i][0]-1] = 1

unsearched_edges = list(range(n))

for i in range(n):
    for j in range(n):
        if d[i] + a[i][j] < d[j]:
            d[j] = d[i] + a[i][j]
            t[j] = i+1
if 0 in t[1:]:
    print("No")
else:
    print('Yes')
    for i in range(1,n):
        print(t[i])

Submission status: Time Limit Exceeded

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

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

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

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

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

# shortestPath = shortest_path(G,target=1)
# shortestPath = single_target_shortest_path(G,target=1)
ans = ["Yes"]
for i in range(2,N+1):
    try:
        shortestPath = astar_path(G,source=i,target=1)
        ans.append(shortestPath[1])
    except:
        print("No")
        exit()

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

Submission status: Time Limit Exceeded

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

print("Yes")
queue = [(e, 1) for e in edge[1]]
while len(queue) > 0:
    # print(queue)
    e, now = queue.pop(0)
    if reached[e] == 0:
        reached[e] = 1
        guide[e] = now
        # edge[e].remove(now)
        for next in edge[e]:
            if next != 1 and reached[next] == 0:
                queue.append((next, e))

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