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:
import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
N, M = LI()
AB = [LI() for _ in range(M)]
path = [[] for _ in range(N+1)]
mp = []
ans = [0] * (N+1)

for ab in AB:
	a = ab[0]
	b = ab[1]
	path[a].append(b)
	path[b].append(a)
	#print(a,b)

def bfs(tree, st, endlist, endnum):
	queue = collections.deque()
	queue.append([-1,st])
	endlist[st] -= 1
	now = [-1,-1,-1]
	pre = []
	depth = 0
	histind = -1
	node = -1
	hist = []
	res = []
	allres = []
	while queue:
		pre = now[:]
		now = queue.popleft()
		histind = now[0]
		node = now[1]
		hist.append([histind,node])
		#来たときは絶対に初回
		res = [node]
		ident = histind
		while res[len(res)-1]!=1:
			res.append(hist[ident][1])
			ident = hist[ident][0]
		allres.append(res[::-1])
		endnum -= 1
		if endnum == 0:
			return allres
		for v in path[node]:
			if endlist[v] > 0:
				queue.append([len(hist)-1,v])
				#endlist更新
				endlist[v] -= 1
		continue
	return None

#print_map(path)
result = bfs(path, 1, [1] * (N+1), N)
#print(result)
if result is None:
	print("No")
	exit(0)
print("Yes")
execnum = N-1
maxlen = len(result[len(result)-1])
for i in result[::-1]:
	for ind,v in enumerate(i[::-1]):
		if v == 1:
			break
		if ans[v] == 0:
			ans[v] = i[len(i)-2-ind]
			execnum-=1
			if execnum == 0:
				break

for i in ans[2:]:
	print(i)

Submission status: Time Limit Exceeded

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
N, M = LI()
AB = [LI() for _ in range(M)]
path = [[] for _ in range(N+1)]
mp = []
ans = [0] * (N+1)

for ab in AB:
	a = ab[0]
	b = ab[1]
	path[a].append(b)
	path[b].append(a)
	#print(a,b)

def bfs(tree, st, endlist, endnum):
	queue = collections.deque()
	queue.append([-1,st])
	endlist[st] -= 1
	now = [-1,-1,-1]
	pre = []
	depth = 0
	histind = -1
	node = -1
	hist = []
	res = []
	allres = []
	while queue:
		pre = now[:]
		now = queue.popleft()
		histind = now[0]
		node = now[1]
		hist.append([histind,node])
		#来たときは絶対に初回
		res = [node]
		ident = histind
		while res[len(res)-1]!=1:
			res.append(hist[ident][1])
			ident = hist[ident][0]
		allres.append(res[::-1])
		endnum -= 1
		if endnum == 0:
			return allres
		for v in path[node]:
			if endlist[v] > 0:
				queue.append([len(hist)-1,v])
				#endlist更新
				endlist[v] -= 1
		continue
	return None

#print_map(path)
result = bfs(path, 1, [1] * (N+1), N)
#print(result)
if result is None:
	print("No")
	exit(0)
print("Yes")
maxlen = len(result[len(result)-1])
for i in result[::-1]:
	for ind,v in enumerate(i[::-1]):
		if v == 1:
			break
		if ans[v] == 0:
			ans[v] = i[len(i)-2-ind]

for i in ans[2:]:
	print(i)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)

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

edge = [[] for i in range(n)]
for i in range(w):
    x, y = map(int, input().split())
    x -= 1
    y -= 1
    edge[x].append(y)
    edge[y].append(x)

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


def dfs(start, d):
    if dist[start] < d:
        return
    for n_r in edge[start]:
        if dist[n_r] > d + 1:
            dist[n_r] = d + 1
            prev[n_r] = start
        else:
            continue
        dfs(n_r, d + 1)


dist[0] = 0
dfs(0, dist[0])
if None in prev[1:]:
    print('No')
else:
    print('Yes')
    for i in prev[1:]:
        print(i + 1)

Submission status: Time Limit Exceeded

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

node = [[] for i in range(n)]
for i in range(m):
    node[ab[i][0] - 1].append(ab[i][1])
    node[ab[i][1] - 1].append(ab[i][0])

# print(node)
node_dic = [[] for i in range(n)]
now = [1]
while True:
    flag = True
    next_node = []
    for i in range(len(now)):
        # print('now: {}'.format(now))
        next_node.append(node[now[i] - 1])
        next_node_element = node[now[i] - 1]
        
        for j in range(len(next_node_element)):
            if not node_dic[next_node_element[j] - 1]:
                node_dic[next_node_element[j] - 1].append(now[i])
                flag = False
    next_node = sum(next_node, [])
    # print('next_node: {}'.format(next_node))
    # print(node_dic)
    now = next_node
    if flag:
        break

for i in range(n):
    if i == 0:
        print('Yes')
        continue
    print(node_dic[i][0])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)

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

edge = [[] for i in range(n)]
for i in range(w):
    x, y = map(int, input().split())
    x -= 1
    y -= 1
    edge[x].append(y)
    edge[y].append(x)

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


def dfs(start):
    for n_r in edge[start]:
        if dist[n_r] > dist[start] + 1:
            dist[n_r] = dist[start] + 1
            prev[n_r] = start
        else:
            continue
        dfs(n_r)


dist[0] = 0
dfs(0)
if None in prev[1:]:
    print('No')
else:
    print('Yes')
    for i in prev[1:]:
        print(i + 1)

Submission status: Time Limit Exceeded

Solution code:
def main():
    input1 = input()
    input1 = input1.split()
    N = int(input1[0])
    M = int(input1[1])

    aisle = [[0 for i in range(N)]for j in range(N)]
    result = [0]*(N-1)
    record = [0]
    count = N-1
    in1 = 0
    in2 = 0

    for i in range(M):
        input2 = input()
        input2 = input2.split()
        in1 = int(input2[0])
        in2 = int(input2[1])
        if in1-1 < in2-1:
            aisle[in1-1][in2-1] = 1
        else:
            aisle[in2-1][in1-1] = 1

    while count != 0 and len(record) != 0:
        pop1 = record.pop(0)
        for i in range(N-1):
            if aisle[pop1][i+1] == 1 and result[i] == 0:
                result[i] = pop1+1
                record.append(i+1)
                count = count - 1
            if aisle[i+1][pop1] == 1 and result[i] == 0:
                result[i] = pop1+1
                record.append(i+1)
                count = count - 1

    if count == 0:
        print("Yes")
        for i in range(len(result)):
            print(result[i])
    else:
        print("No")


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    input1 = input()
    input1 = input1.split()
    N = int(input1[0])
    M = int(input1[1])

    aisle = [[0 for i in range(N)]for j in range(N)]
    result = [0]*(N-1)
    record = [0]
    count = N-1
    in1 = 0
    in2 = 0
    for i in range(M):
        input2 = input()
        input2 = input2.split()
        in1 = int(input2[0])
        in2 = int(input2[1])
        if in1-1 < in2-1:
            aisle[in1-1][in2-1] = 1
        else:
            aisle[in2-1][in1-1] = 1

    while count != 0 and len(record) != 0:
        pop1 = record.pop(0)
        for i in range(N-1):
            if aisle[pop1][i+1] == 1 and result[i] == 0:
                result[i] = pop1+1
                record.append(i+1)
                count = count - 1
            if aisle[i+1][pop1] == 1 and result[i] == 0:
                result[i] = pop1+1
                record.append(i+1)
                count = count - 1

    if count == 0:
        print("Yes")
    else:
        print("No")
    for i in range(len(result)):
        print(result[i])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

root = [[pow(10,9)]*n for _ in range(n)]

from collections import deque

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

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

dist =[-1]*n
dist[0] = 0

q = deque([0])
prev=[-1] * n

while q:
    v = q.popleft()

    for j in r[v]:
        if prev[j]!=-1:
            continue
        else:
            # dist[j] = dist[v] + 1
            prev[j] = v
            q.append(j)


for i in range(n):
    if i==0:
        print('Yes')
    else:
        print(prev[i]+1)

Submission status: Time Limit Exceeded

Solution code:

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

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


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

st = [0]*(n+1)
st[1] = 1
sti = 2
f[1] = 0

for i in range(1, n + 1):
    for j in p[st[i]]:
        if f[j] == -1:
            st[sti] = j
            f[j] = st[i]
            sti += 1
        if sti == n+1:
            print("Yes")
            for k in range(2, n+1):
                print(f[k])
            exit()

Submission status: Time Limit Exceeded

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

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

q = [0]
ans = [-1] * N
while(len(q) > 0):
    now = q.pop(0)

    for i in node[now]:
        if ans[i] == -1:
            q.append(i)
            ans[i] = now


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

Submission status: Time Limit Exceeded

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

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

q = [0]
ans = [-1] * N
kyo = [99999999999999] * N
kyo[0] = 0
while(len(q) > 0):
    now = q.pop()
    for i in node[now]:
        if kyo[i] > kyo[now] + 1:
            q.append(i)
            ans[i] = now
            kyo[i] = kyo[now] + 1


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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
route = [[0] * n for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    route[a-1][b-1] = 1
    route[b-1][a-1] = 1

q = deque()
visited = [0] * n
pre = [-1] * n
q.append(0)
visited[0] = 1
while q:
    # visitした
    v = q.popleft()
    for i in range(n):
        if visited[i] == 1 or route[v][i] == 0: continue
        visited[i] = 1
        pre[i] = v
        q.append(i)
print("Yes")
for p in pre[1:]:
    p += 1
    print(p)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
INF = 10**9 + 7
n, m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n+1)]
for a, b in ab:
    g[a].append([a, b])
    g[b].append([b, a])
res = [[0, INF] for _ in range(n+1)]
res[1][0] = 1
res[1][1] = 0
q = deque(g[1])
while q:
    q_ = q.pop()
    if res[q_[1]][1] == INF or res[q_[1]][1] > res[q_[0]][1] + 1:
        for gi in g[q_[1]]: q.append(gi)
        res[q_[1]][0] = q_[0]
        res[q_[1]][1] = res[q_[0]][1] + 1
print("Yes")
for i in res[2:]: print(i[0])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

ans = [0] * (n - 1) 
seen = deque([1])
not_seen = [True] * n
not_seen[0] = False

while sum(not_seen) > 0:
    pre = seen.popleft()
    for now in path[pre]:
        if not_seen[now - 1]:
            #print(now, pre)
            seen.append(now)
            ans[now - 2] = pre
            not_seen[now - 1] = False
            #print(ans)

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

Submission status: Time Limit Exceeded

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

ans = [0] * (n - 1) 
seen = [1]
not_seen = [True] * n
not_seen[0] = False

while sum(not_seen) > 0:
    pre = seen.pop(0)
    for now in path[pre]:
        if not_seen[now - 1]:
            #print(now, pre)
            seen.append(now)
            ans[now - 2] = pre
            not_seen[now - 1] = False
            #print(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
n,m = map(int, sys.stdin.readline().rstrip("\n").split())
cage = {}
for i in range (2,n+1):
    cage[i] = None
ab = [map(int, line.rstrip("\n").split()) for line in sys.stdin]
a,b = [list(i) for i in zip(*ab)]
room = [1]
nroom = []
while None in cage.values():
    for i in range(len(room)):
        j = 0
        while j < (len(a)):
            if a[j] == room[i]:
                if cage[b[j]] == None:
                    cage[b[j]] = a[j]
                nroom.append(b[j])
                a.pop(j)
                b.pop(j)
            elif b[j] == room[i]:
                if cage[a[j]] == None:
                    cage[a[j]] = b[j]
                nroom.append(a[j])
                a.pop(j)
                b.pop(j)
            else:
                j += 1
    if room == nroom:
        print('No')
        break
    room = nroom[:]
    nroom.clear()
else:
    print('Yes')
    for i in range (2,n+1):
        print(cage[i])

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split())
box=[[] for i in range(N)]
for i in range(M):
    a,b=map(int,input().split())
    box[a-1].append(b-1)
    box[b-1].append(a-1)
ans=[None]*(N)
ans[0]=0
que=[0]
while len(que)>0:
    index=que.pop(0)
    for x in box[index]:
        if ans[x]==None:
            ans[x]=index+1
            que.append(x)
print("Yes")
for i in range(1,N):
    print(ans[i])

Submission status: Time Limit Exceeded

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_edges_from(s)
 
print("Yes")
for x in sorted(nx.bfs_predecessors(g,1)):
    print(x[1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

from collections import deque

N,M = map(int,input().split())
AB = deque()
for i in range(0,M):
    AB.append(list(map(int,input().split())))
#[list(map(int,input().split())) for x in range(0,M)]

ans = [0]*(N+1)
ans[1] = 1

start = 1
d = deque([start])

while len(AB)>0:
    itnum_d = len(d)

    for ii in range(0,itnum_d):
        itnum = len(AB)
        start = d.popleft()

        for i in range(0,itnum):

            check = AB.popleft()

            if ans[check[0]] != 0 and ans[check[1]] != 0:
                continue

            if check[0] == start:
                ans[check[1]] = start
                d.append(check[1])
            elif check[1] == start:
                ans[check[0]] = start
                d.append(check[0])
            else:
                AB.append(check)

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

Submission status: Time Limit Exceeded

Solution code:
class Node:
    nodeList = {}

    def __init__(self, value):
        self.value = value
        Node.nodeList[value] = self
        self.connections = []

    def addConnection(self, value):
        if value in self.connections:
            return
        if value in Node.nodeList:
            self.connections.append(value)
        else:
            self.connections.append(Node(value))

    def __str__(self):
        return f'{self.value} is connected to {self.connections}'

    def pathTo(self, value):
        # queue stores nodes as {value: int, parent: parent value}
        path = []
        daude = value
        self.queue = [{'value': self.value, 'parent': None}]
        self.visited = []
        while self.queue and daude not in [i['value'] for i in self.queue]:
            self.visited.append(self.queue[0])
            lst = []
            val = self.queue[0]['value']
            for i in Node.nodeList[val].connections:
                if i in [k['value'] for k in self.queue] or i in [k['value'] for k in self.visited]:
                    continue
                self.queue.append({'value': i, 'parent': val})
            del self.queue[0]
        if len(self.queue) == 0:
            return [-1, -1]
        parent = [i['parent'] for i in self.queue if i['value'] == daude][0]
        path.append(daude)
        while parent:
            path.append(parent)
            if parent in [i['value'] for i in self.visited]:
                parent = [i['parent'] for i in self.visited if i['value'] == parent][0]
            elif parent in [i['value'] for i in self.queue]:
                parent = [i['parent'] for i in self.queue if i['value'] == parent][0]
        if path:
            return path
        else:
            return [-1, -1]



# input_file = '''6 9
# 3 4
# 6 1
# 2 4
# 5 3
# 4 6
# 1 5
# 6 2
# 4 5
# 5 6'''
# input_file = input_file.split('\n')
# print(input_file)
# input_file = [[int(j[0]), int(j[1])] for j in [i.split() for i in input_file]]
num_lines = [int(i) for i in input().split()]
input_file = [num_lines]
for i in range(num_lines[1]):
    input_file.append([int(i) for i in input().split()])
for i in input_file[1:]:
    for k in i:
        if k in Node.nodeList:
            continue
        Node(k)
    Node.nodeList[i[0]].addConnection(i[1])
    Node.nodeList[i[1]].addConnection(i[0])
signs = []
for i in range(2, input_file[0][0] + 1):
    sign = Node.nodeList[1].pathTo(i)[1]
    if sign == -1:
        print('No')
        quit()
    else:
        signs.append(sign)
print('Yes')
print('\n'.join([str(i) for i in signs]))

Submission status: Time Limit Exceeded

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

node = [float('inf')] * N
node[0] = 0 #1までの距離
route = [0]*N #ランプ置く部屋
rooms = [1] #次調べる部屋

for r1 in rooms:
    for r2 in dic[r1]:
        if node[r1-1] + 1 <= node[r2-1]:
            node[r2-1] = node[r1-1] + 1
            route[r2-1] = r1
            if not r2 in rooms:
                rooms.append(r2)
            try:
                dic[r2].remove(r1)
            except:
                continue

if float('inf') in node:
    print('No')
else:
    print('Yes')
    for i in route[1:]:
        print(i)

Submission status: Time Limit Exceeded

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

node = [float('inf')] * N
node[0] = 0 #1までの距離
route = [0]*N #ランプ置く部屋
rooms = [1] #次調べる部屋

for r1 in rooms:
    for r2 in dic[r1]:
        if node[r1-1] + 1 <= node[r2-1]:
            node[r2-1] = node[r1-1] + 1
            route[r2-1] = r1
            rooms.append(r2)
            try:
                dic[r2].remove(r1)
            except:
                continue

if float('inf') in node:
    print('No')
else:
    print('Yes')
    for i in route[1:]:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n,m = map(int, input().split())
dic = {}

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

dic = [[] for _ in range(n + 1)]

for a,b in AB:
    a -= 1
    b -= 1

    dic[a].append(b)
    dic[b].append(a)

#dist = {}
queue = deque([0])
visited = []
pre = {}

#dist[0] = 0 
queue.append(0)

while queue:
    v = queue.popleft()
    
    for i in dic[v]:
        if i in visited:
            continue
        
        visited.append(i)
        #dist[i] = dist[v] + 1
        pre[i]= v
        queue.append(i)

print("Yes")
for i in range(n):
    ans = 0
    
    if(i == 0):
        continue
    
    ans = pre[i]
    ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n,m = map(int, input().split())
dic = {}

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

dic = [[] for _ in range(n + 1)]

for a,b in AB:
    a -= 1
    b -= 1

    dic[a].append(b)
    dic[b].append(a)

dist = {}
queue = deque([0])
visited = []
pre = {}

dist[0] = 0 
#queue.append(0)

while queue:
    v = queue.popleft()
    
    for i in dic[v]:
        if i in visited:
            continue
        
        visited.append(i)
        dist[i] = dist[v] + 1
        pre[i]= v
        queue.append(i)


print("Yes")
for i in range(n):
    ans = 0
    
    if(i == 0):
        continue
    
    ans = pre[i]
    ans += 1
    print(ans)

Submission status: Time Limit Exceeded

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

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

dic = [[] for _ in range(n + 1)]

for a,b in AB:
    a -= 1
    b -= 1

    dic[a].append(b)
    dic[b].append(a)

dist = {}
queue = []
visited = []
pre = {}

dist[0] = 0 
queue.append(0)

while len(queue) > 0:
    v = queue.pop(0)
    
    for i in dic[v]:
        if i in visited:
            continue
        
        visited.append(i)
        dist[i] = dist[v] + 1
        pre[i]= v
        queue.append(i)


print("Yes")
for i in range(n):
    ans = 0
    
    if(i == 0):
        continue
    
    ans = pre[i]
    ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


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

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

#print(dct)
answers = deque([0]*(N+1))

stack = deque([1])
lst = set()
while len(stack):
    s = stack.popleft()
    lst.add(s)
    #print(dct[s])
    for i in dct[s]:
        if i in lst:
            continue
        if i in stack:
            continue
        stack.append(i)
        answers[i] = s

print("Yes")
answers.popleft()
answers.popleft()
for ans in answers:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
graph = [0]*(N+1)
for i in range(N+1):
    graph[i]=list()
for i in range(M):#生成
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
graph[0].append(1)
# for i in range(N+1):#整列
#     graph[i].sort()
# print(graph)
ans = [0]*(N+1)
dis_stack = list()
dis_stack.extend(graph[0])
bef_stack = [1]
# k = 0
# print(graph)
while(len(dis_stack)!=0):
    now_watch=dis_stack.pop(0)
    next_watch = graph[now_watch]
    for spot in next_watch:
        if(spot in bef_stack):
            pass
        else:
            # print(dis_stack)
            # print(bef_stack)
            dis_stack.append(spot)
            ans[spot] = now_watch
            # print(ans)
        bef_stack.append(spot)
 
ans.pop(0)
print("Yes")
for i in range(1,len(ans)):
    print(ans[i])

    # k +=1
# 探索スタート地点を「探索候補スタック」に積む
# while スタックが空っぽになるまで
#     スタックから次の探索地点を1つ取り出す（pop）
#     「探索済みリスト」に取り出した地点を格納（ここが現在地点）
# 　　現在地点から、次に行こうと思えば行けるポイントを全部探し出す
#     for 地点 in 次に行こうと思えば行けるポイント
#         if その地点は既に「探索済みリスト」にある？
#             探索済みなので「探索候補スタック」には入れない（continue）
#         if その地点は既に「探索候補スタック」にある？（閉路があるなら可能性あり、木なら可能性なし）
#             探索予定なので「探索候補スタック」には入れない（continue）
#         未探索かつ候補にも入っていない地点なので「探索候補スタック」に追加する（append）
# print 探索済み地点

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int, input().split())
dic = {}
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    
    if a in dic.keys():
        tmp = dic[a]
        tmp.append(b)
        dic[a] = tmp
    else:
        tmp = [b]
        dic[a] = tmp
    
    if b in dic.keys():
        tmp = dic[b]
        tmp.append(a)
        dic[b] = tmp
    else:
        tmp = [a]
        dic[b] = tmp

dist = {}
queue = []
visited = []
pre = {}

dist[0] = 0 
queue.append(0)

while len(queue) > 0:
    v = queue.pop(0)
    
    for i in dic[v]:
        if i in visited:
            continue
        
        visited.append(i)
        dist[i] = dist[v] + 1
        pre[i]= v
        queue.append(i)


print("Yes")
for i in range(n):
    ans = 0
    
    if(i == 0):
        continue
    
    ans = pre[i]
    ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
graph = [0]*(N+1)
for i in range(N+1):
    graph[i]=list()
for i in range(M):#生成
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
graph[0].append(1)
for i in range(N+1):#整列
    graph[i].sort()
# print(graph)
ans = [0]*(N+1)
dis_stack = list()
dis_stack.extend(graph[0])
bef_stack = [1]
# k = 0
# print(graph)
while(len(dis_stack)!=0):
    now_watch=dis_stack.pop(0)
    next_watch = graph[now_watch]
    for spot in next_watch:
        if(spot in bef_stack):
            pass
        else:
            # print(dis_stack)
            # print(bef_stack)
            dis_stack.append(spot)
            ans[spot] = now_watch
            # print(ans)
        bef_stack.append(spot)
 
ans.pop(0)
print("Yes")
for i in range(1,len(ans)):
    print(ans[i])

    # k +=1
# 探索スタート地点を「探索候補スタック」に積む
# while スタックが空っぽになるまで
#     スタックから次の探索地点を1つ取り出す（pop）
#     「探索済みリスト」に取り出した地点を格納（ここが現在地点）
# 　　現在地点から、次に行こうと思えば行けるポイントを全部探し出す
#     for 地点 in 次に行こうと思えば行けるポイント
#         if その地点は既に「探索済みリスト」にある？
#             探索済みなので「探索候補スタック」には入れない（continue）
#         if その地点は既に「探索候補スタック」にある？（閉路があるなら可能性あり、木なら可能性なし）
#             探索予定なので「探索候補スタック」には入れない（continue）
#         未探索かつ候補にも入っていない地点なので「探索候補スタック」に追加する（append）
# print 探索済み地点

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


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

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

#print(dct)
answers = deque([0]*(N+1))

stack = deque([1])
lst = []
while len(stack):
    s = stack.popleft()
    lst.append(s)
    #print(dct[s])
    for i in dct[s]:
        if i in lst:
            continue
        if i in stack:
            continue
        stack.append(i)
        answers[i] = s

print("Yes")
answers.popleft()
answers.popleft()
for ans in answers:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m = map(int, input().split())
dic = {}
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    
    if a in dic.keys():
        tmp = dic[a]
        tmp.append(b)
        dic[a] = tmp
    else:
        tmp = [b]
        dic[a] = tmp
    
    if b in dic:
        tmp = dic[b]
        tmp.append(a)
        dic[b] = tmp
    else:
        tmp = [a]
        dic[b] = tmp

dist = {}
queue = []
visited = []
pre = {}

dist[0] = 0 
queue.append(0)

while len(queue) > 0:
    v = queue.pop(0)
    
    for i in dic[v]:
        if i in visited:
            #print(visited)
            continue
        
        visited.append(i)
        dist[i] = dist[v] + 1
        pre[i]= v
        queue.append(i)


print("Yes")
for i in range(n):
    ans = 0
    
    if(i == 0):
        continue
    
    ans = pre[i]
    ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


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

dct = {}
for _ in range(M):
    a, b = map(int,input().split())
    if not a in dct:
        dct[a] = set()
    if not b in dct:
        dct[b] = set()
    dct[a].add(b)
    dct[b].add(a)

#print(dct)
answers = deque([0]*(N+1))

stack = deque([1])
lst = []
while len(stack):
    s = stack.popleft()
    lst.append(s)
    #print(dct[s])
    for i in dct[s]:
        if i in lst:
            continue
        if i in stack:
            continue
        stack.append(i)
        answers[i] = s

if answers.count(0) != 2:
    print("No")
else:
    print("Yes")
    answers.popleft()
    answers.popleft()
    
    for ans in answers:
        print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split())
AB=[list(map(int,input().split())) for i in range(M)]
goto=[[] for i in range(N+1)]
for i in range(M):
    goto[AB[i][0]].append(AB[i][1])
    goto[AB[i][1]].append(AB[i][0])
#print(goto)

from collections import deque
from sys import exit
AB=deque(AB)
rank=[[1]]
flag=1

while len(AB)>0:
    l=len(AB)
    rank.append([])
    for i in range(l):
        ab=AB.popleft()
        if ab[0] in rank[-2] and ab[1] not in rank[-2]:
            rank[-1].append(ab[1])
        elif ab[1] in rank[-2] and ab[0] not in rank[-2]:
            rank[-1].append(ab[0])
        elif ab[0] not in rank[-2] and ab[1] not in rank[-2]:
            AB.append(ab)
    if l==len(AB):
        print('No')
        exit()

#print(rank)
print('Yes')
rank2=[-1 for i in range(N+1)]
rank2[1]=0
for i in range(1,len(rank)):
    for j in range(len(rank[i])):
        rank2[rank[i][j]]=i

#print(rank2)

for i in range(2,N+1):
    s=set(goto[i])&set(rank[rank2[i]-1])
    print(list(s)[0])