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 math
import queue
from collections import defaultdict
import itertools as it
import copy

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()
def factorization(n):
	res = []
	if n%2==0:
		res.append(2)
	for i in range(3,math.floor(n//2)+1,2):
		if n%i==0:
			c = 0
			for j in res:
				if i%j==0:
					c=1
			if c==0:
				res.append(i)
	return res
def fact2(n):
	p = factorization(n)
	res = []
	for i in p:
		c=0
		z=n
		while 1:
			if z%i==0:
				c+=1
				z/=i
			else:
				break
		res.append([i,c])
	return res
def fact(n):#階乗
	ans = 1
	m=n
	for _i in range(n-1):
		ans*=m
		m-=1
	return ans
def comb(n,r):#コンビネーション
	if n<r:
		return 0
	l = min(r,n-r)
	m=n
	u=1
	for _i in range(l):
		u*=m
		m-=1
	return u//fact(l)
def combmod(n,r,mod):
	return (fact(n)/fact(n-r)*pow(fact(r),mod-2,mod))%mod
def printQueue(q):
	r=copyQueue(q)
	ans=[0]*r.qsize()
	for i in range(r.qsize()-1,-1,-1):
		ans[i] = r.get()
	print(ans)
def dq():
	return queue.deque()
class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1]*n

	def find(self, x): # root
		if self.parents[x]<0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self,x,y):
		x = self.find(x)
		y = self.find(y)

		if x==y:
			return

		if self.parents[x]>self.parents[y]:
			x,y = y,x

		self.parents[x]+=self.parents[y]
		self.parents[y]=x

	def size(self,x):
		return -1*self.parents[self.find(x)]

	def same(self,x,y):
		return self.find(x)==self.find(y)

	def members(self,x): # much time
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i)==root]

	def roots(self):
		return [i for i,x in enumerate(self.parents) if x<0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()} # 1~n
def bitArr(n):#ビット全探索
	x = 1
	zero = "0"*n
	ans = []
	ans.append([0]*n)
	for i in range(2**n-1):
		ans.append(list(map(lambda x:int(x),list((zero+bin(x)[2:])[-1*n:]))))
		x+=1
	return ans;
def arrsSum(a1,a2):
	for i in range(len(a1)):
		a1[i]+=a2[i]
	return a1
def maxValue(a,b,v):
	v2 = v
	for i in range(v2,-1,-1):
		for j in range(v2//a+1): #j:aの個数
			k = i-a*j
			if k%b==0:
				return i
	return -1
def copyQueue(q):
	nq = queue.Queue()
	n = q.qsize()
	for i in range(n):
		x = q.get()
		q.put(x)
		nq.put(x)
	return nq

def addRoad(a,b):
	global ab
	if ab[a][0]==0:
		ab[a][0]=b
	else:
		ab[a].append(b)
	if ab[b][0]==0:
		ab[b][0]=a
	else:
		ab[b].append(a)
def addFlag(fr,toArr):
	global flg
	for to in toArr:
		if flg[to]==-1:
			flg[to]=fr
def addQueue(arr):
	global q
	for i in arr:
		q.put(i)


n,m = readInts()
ab = [[0] for i in range(n+1)]
for i in range(m):
	a,b = readInts()
	addRoad(a,b)

q = queue.Queue()
flg = [-1]*(n+1)
flg[0] = 0
flg[1] = 0
q.put(1)

while -1 in flg or q.empty():
	item = q.get()
	addFlag(item,ab[item])
	addQueue(ab[item])

if -1 in flg:
	print("No")
	exit()

print("Yes")
for i in range(2,len(flg)):
	print(flg[i])

Submission status: Time Limit Exceeded

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
#dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])}
ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda :int(input())
ip = lambda :[int(w) for w in input().split()]

n,m = ip()
graph = {i:[] for i in range(1,n+1)}
for i in range(m):
    a,b = ip()
    graph[a].append(b)
    graph[b].append(a)

start = 1
nodes = list(graph.keys())
d = {i:float('inf') for i in nodes}
parent = {i:-1 for i in nodes}
q = set([i for i in nodes])
vis = {i:1 for i in nodes}
d[start] = 0

while len(q):
    mn = float('inf')
    for v in nodes:
        if d[v] < mn and vis[v]:
            mn = d[v]
            u = v
    q.remove(u)
    vis[u] = 0
    for v in graph[u]:
        if d[u]+1 < d[v] and vis[v]:
            d[v] = d[u] + 1
            parent[v] = u

if float('inf') in list(d.values()):
    print("No")
    exit()
print("Yes")
for i in range(2,n+1):
    print(parent[i])

Submission status: Time Limit Exceeded

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

def main():
  N, M = map(int, readline().split())
  dist = {}
  pre = {}
  A = {}
  for i in range(N):
    dist[i+1] = -1
    pre[i+1] = -1
    A[i+1] = []
  dist[1] = 0
  pre[1] = 0
  for i in range(M):
    ai, bi = map(int, readline().split())
    if bi not in A[ai]:
      A[ai].append(bi)
    if ai not in A[bi]:
      A[bi].append(ai)
  cnt = 1
  depth = 1
  D = [1]
  while cnt < N:
    next = []
    for i in range(len(D)):
      for j in range(len(A[D[i]])):
        if dist[A[D[i]][j]] == -1:
          dist[A[D[i]][j]] = depth
          pre[A[D[i]][j]] = D[i]
          next.append(A[D[i]][j])
          cnt += 1
    D = next
    depth += 1
    if len(next) == 0:
      break
    elif depth > N:
      break
  if cnt == N:
    print('Yes')
    for i in range(1, N):
      print(pre[i+1])
  else:
    print('No')

if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from scipy.sparse.csgraph import dijkstra
    from scipy.sparse import csr_matrix
    import numpy as np
    n, m = map(int, input().split())
    edge = np.array([input().split() for _ in range(m)], dtype=np.int64).T
    a = csr_matrix(([1] * m, (edge - 1)), shape=(n, n))
    p = dijkstra(a, return_predecessors=True, min_only=True, limit=n+1, indices=0, directed=False, unweighted=True)
    if min(p[1][1:]) < -1:
        print("No")
    else:
        print("Yes")
        for i in p[1][1:]:
            print(i + 1)


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
#dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])}
ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda :int(input())
ip = lambda :[int(w) for w in input().split()]

n,m = ip()
graph = {i:[] for i in range(1,n+1)}
for i in range(m):
    a,b = ip()
    graph[a].append(b)
    graph[b].append(a)

start = 1
nodes = list(graph.keys())
d = {i:float('inf') for i in nodes}
parent = {i:-1 for i in nodes}
q = set([i for i in nodes])
d[start] = 0

while len(q):
    mn = float('inf')
    for v in nodes:
        if d[v] < mn and v in q:
            mn = d[v]
            u = v
    q.remove(u)
    for v in graph[u]:
        if d[u]+1 < d[v] and v in q:
            d[v] = d[u] + 1
            parent[v] = u

if float('inf') in list(d.values()):
    print("No")
    exit()
print("Yes")
for i in range(2,n+1):
    print(parent[i])

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from scipy.sparse.csgraph import dijkstra
    from scipy.sparse import csr_matrix
    import numpy as np
    n, m = map(int, input().split())
    edge = np.array([input().split() for _ in range(m)], dtype=np.int64).T
    a = csr_matrix(([1] * m, (edge - 1)), shape=(n, n))
    p = dijkstra(a, return_predecessors=True, min_only=True, indices=0, directed=False, unweighted=True)
    if min(p[1][1:]) < -1:
        print("No")
    else:
        print("Yes")
        for i in p[1][1:]:
            print(i + 1)


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p1 = []
p2 = []
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p1.append(a)
    p2.append(b)
d = [1, ]
c = [0, ]
l = 0
flag = True
for j in range(1, n):
    for i, t in enumerate(p1):
        if t == d[l]:
            d.append(p2[i])
            c.append(t)
    for i, t in enumerate(p2):
        if t == d[l]:
            d.append(p1[i])
            c.append(t)
    if len(d) > l:
        l += 1
    else:
        flag = False
        break
con = []
for i in range(2, n+1):
    for y, j in enumerate(d):
        flfl = True
        if j == i:
            con.append(c[y])
            flfl=False
            break
        if not flfl:
            break
    if flfl:
        con.append(0)
        break

if 0 in con:
    print('No')
else:
    print('Yes')
    for i in con:
        print(i)

Submission status: Time Limit Exceeded

Solution code:

room,path = map(int,input().split())
dic = {}
ans_dic = {}
g = [1]
g_m = []

def re(li,i):
    if li[0] == i:
        return li[1]
    else:
        return li[0]

def pile_del(g):
    t = []
    for key,i in dic.items():
        if i[0] in g and  i[1] in g:
            t.append(key)
    for i in t:
        dic.pop(i)
    return 0

def main(ans_dic,dic,k):
    dele = []
    g_m = []
    for key,j in dic.items():
        if k in j :
            ans_dic[re(j,k)] = j
            dele.append(key)
            g.append(re(j,k))
            g_m.append(re(j,k))
    for i in dele:
        dic.pop(i)
    pile_del(g_m)

for i in range(path):
    dic[i+1] = list(map(int,input().split()))

for key,i in dic.items():
    if 1 in i :
        if i[0] == 1:
            g.append(re(i,i[0]))
            ans_dic[i[1]] = i
        else:
            g.append(re(i,i[1]))
            ans_dic[i[0]] = i

pile_del(g)
li_c = len(dic)

if li_c != 0:
    for k in g:
        main(ans_dic,dic,k)

while li_c != len(dic) and li_c != 0:
    li_c = len(dic)
    for k in g_m:
        main(ans_dic,dic,k)

if len(ans_dic) == room-1:
    print("Yes")
    for i in range(room-1):
        print(re(ans_dic[i+2],i+2))
else:
    print("No")
# print(ans_dic)

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
from pprint import pprint

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)

room_connection = [[] for n in range(N)]

for a, b in zip(A, B):
    room_connection[a - 1].append(b - 1)
    room_connection[b - 1].append(a - 1)

room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

stack = [0]
visited = []

# pprint(room_connection)

while stack:
    now = stack.pop()
    next_room = [r for r in room_connection[now] if r not in visited]
    # print('now=', now)
    # print('next_room', next_room)

    for r in next_room:
        if r not in visited or r not in stack:
            stack.append(r)

        if room_depth[r] is None or room_depth[r] > room_depth[now] + 1:
            room_depth[r] = room_depth[now] + 1
            room_sign[r] = now + 1

    visited.append(now)

    if set(visited) == set(range(N)):
        break


    # print('visited', visited)
    # print('depth', room_depth)
    # print('stack', stack)
    # print('sign', room_sign)
    # print('-----')

print('Yes')
for s in room_sign[1:]:
    print(s)

Submission status: Time Limit Exceeded

Solution code:

room,path = map(int,input().split())
dic = {}
ans_dic = {}
g = [1]
g_m = []

def re(li,i):
    if li[0] == i:
        return li[1]
    else:
        return li[0]

def pile_del(g):
    t = []
    for key,i in dic.items():
        if i[0] in g and  i[1] in g:
            t.append(key)
    for i in t:
        dic.pop(i)
    return 0

def main(ans_dic,dic,k):
    dele = []
    for key,j in dic.items():
        if k in j :
            ans_dic[re(j,k)] = j
            dele.append(key)
            g.append(re(j,k))
            g_m.append(re(j,k))
    for i in dele:
        dic.pop(i)
    pile_del(g_m)

for i in range(path):
    dic[i+1] = list(map(int,input().split()))

for key,i in dic.items():
    if 1 in i :
        if i[0] == 1:
            g.append(re(i,i[0]))
            # g_m.append(re(i,i[0]))
            ans_dic[i[1]] = i
        else:
            g.append(re(i,i[1]))
            # g_m.append(re(i,i[1]))
            ans_dic[i[0]] = i

pile_del(g)

li_c = len(dic)

if li_c != 0:
    for k in g:
        main(ans_dic,dic,k)

while li_c != len(dic) and li_c != 0:
    li_c = len(dic)
    for k in g:
        main(ans_dic,dic,k)



if len(ans_dic) == room-1:
    print("Yes")
    for i in range(room-1):
        print(re(ans_dic[i+2],i+2))
else:
    print("No")
# print(ans_dic)

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
from pprint import pprint

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)

room_connection = [[] for n in range(N)]

for a, b in zip(A, B):
    room_connection[a - 1].append(b - 1)
    room_connection[b - 1].append(a - 1)

room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

stack = [0]
visited = []

while stack:
    now = stack.pop()
    next_room = [r for r in room_connection[now] if r not in visited]
    # print('now=', now)
    # print('next_room', next_room)

    for r in next_room:
        if r not in visited or r not in stack:
            stack.append(r)

        if room_depth[r] is None or room_depth[r] > room_depth[now] + 1:
            room_depth[r] = room_depth[now] + 1
            room_sign[r] = now + 1

    visited.append(now)

    if visited == range(N):
        break

    # print('visited', visited)
    # print('depth', room_depth)
    # print('stack', stack)
    # print('sign', room_sign)
    # print('-----')

print('Yes')
for s in room_sign[1:]:
    print(s)

Submission status: Time Limit Exceeded

Solution code:

room,path = map(int,input().split())
dic = {}
ans_dic = {}
g = [1]

def re(li,i):
    if li[0] == i:
        return li[1]
    else:
        return li[0]

def pile_del(g):
    t = []
    for key,i in dic.items():
        if i[0] in g and  i[1] in g:
            t.append(key)
    for i in t:
        dic.pop(i)
    return 0

for i in range(path):
    dic[i+1] = list(map(int,input().split()))

for key,i in dic.items():
    if 1 in i :
        if i[0] == 1:
            g.append(re(i,i[0]))
            ans_dic[i[1]] = i
        else:
            g.append(re(i,i[1]))
            ans_dic[i[0]] = i

# print(g)
pile_del(g)

def main(ans_dic,dic,k):
    dele = []
    for key,j in dic.items():
        if k in j :
            ans_dic[re(j,k)] = j
            dele.append(key)
            g.append(re(j,k))
    for i in dele:
        dic.pop(i)
    pile_del(g)
    # print(k)
    # print(dic)
    # print(ans_dic)

li_c = len(dic)

if li_c != 0:
    for k in g:
        main(ans_dic,dic,k)

while li_c != len(dic) and li_c != 0:
    li_c = len(dic)
    for k in g:
        main(ans_dic,dic,k)



if len(ans_dic) == room-1:
    print("Yes")
    for i in range(room-1):
        print(re(ans_dic[i+2],i+2))
else:
    print("No")
# print(ans_dic)

Submission status: Time Limit Exceeded

Solution code:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p1 = []
p2 = []
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p1.append(a)
    p2.append(b)
d = [[1], ]
c = [[0], ]
l = 0
flag = True
for j in range(1, n):
    a = []
    b = []
    for i, t in enumerate(p1):
        for h in d[l]:
            if t == h:
                a.append(p2[i])
                b.append(t)
    for i, t in enumerate(p2):
        for h in d[l]:
            if t == h:
                a.append(p1[i])
                b.append(t)
    d.append(a)
    c.append(b)
    if len(d) > l:
        l += 1
    else:
        flag = False
        break
con = []
for i in range(2, n+1):
    for y, j in enumerate(d):
        flfl = True
        if i in j:
            for w, k in enumerate(j):
                if k == i:
                    con.append(c[y][w])
                    flfl=False
                    break
        if not flfl:
            break
    if flfl:
        con.append(0)
        break

if 0 in con:
    print('No')
else:
    print('Yes')
    for i in con:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
room, route_count = map(int,input().split())
route = np.array([list(map(int,input().split())) for _ in range(route_count)])
 
object_nums = [1]
ans = np.array([0]*(room-1))
 
def mem_ans(ans, object_num, next_nums):
    mask_array = np.zeros(room-1, dtype=bool)
    mask_array[next_nums-2] = True
    ans[(ans==0) & mask_array] = object_num
    return ans
 
for object_num in object_nums:
    object_num_mask = np.any(route==object_num, axis=1)
    object_rows = route[object_num_mask]
    route = route[~object_num_mask]
    next_nums = object_rows[object_rows!=object_num]
    if next_nums is not None:
        ans = mem_ans(ans, object_num, next_nums)
        object_nums.extend(next_nums)
    else:
        break
 
if 0 in set(ans):
  print('No')
else:
  print('Yes')
  for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
room, route_count = map(int,input().split())
route = np.array([list(map(int,input().split())) for _ in range(route_count)])
 
object_nums = [1]
ans = np.array([0]*(room-1))
 
def mem_ans(ans, object_num, next_nums):
    mask_array = np.zeros(room-1, dtype=bool)
    mask_array[next_nums-2] = True
    ans[(ans==0) & mask_array] = object_num
    return ans
 
for object_num in object_nums:
 
    object_rows = route[np.any(route==object_num, axis=1)]
    route[np.any(route==object_num, axis=1)] = 0
    next_nums = object_rows[object_rows!=object_num]
    if next_nums is not None:
        ans = mem_ans(ans, object_num, next_nums)
        object_nums.extend(next_nums)
    else:
        break
 
if 0 in set(ans):
  print('No')
else:
  print('Yes')
  for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque

N, M = map(int, input().split())
d = deque()
ans = defaultdict(int)
pre = []

for _ in range(M):
    A, B = map(int, input().split())
    if A == 1:
        ans[B] = 1
        pre.append(B)
    elif B == 1:
        ans[A] = 1
        pre.append(A)
    else:
        d.append([A,B])


while d and pre:
    c = []
    for _ in range(len(d)):
        A, B = d.popleft()
        
        if A in pre:
            if not ans[B]:
                ans[B] = A
                c.append(B)
        
        elif B in pre:
            if not ans[A]:
                ans[A] = B
                c.append(A)

        else:
            d.append([A,B])
    pre = c

if len(ans) < N-1:
    print("No")
else:
    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())

routes = []
for i in range(m):
    x,y = map(int, input().split())
    routes.append([x-1,y-1])
    # routes[i] = routes[i] - [1,1] #道の番号をずらす

rooms = [0 for i in range(n)] # 行ったら1,まだなら0
marks = [0 for i in range(n)] # 部屋におく道標
roads = [0 for i in range(m)]
rooms_rate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1

turn = 0
for i in rooms_rate:
    newrate = []
    for j in rooms_rate[turn]: #turn回目に行ける部屋を調べる
        for k in range(m):
            if(roads[k] == 1):
                continue
            else:
                a = routes[k][0]
                b = routes[k][1]
            if (j == a and rooms[b] == 0):
                rooms[b] = 1
                marks[b] = a
                newrate.append(b)
                roads[k] = 1
            elif (j == b and rooms[a] == 0):
                rooms[a] = 1
                marks[a] = b
                newrate.append(a)
                roads[k] = 1
    rooms_rate.append(newrate)
    if (len(newrate) == 0):
        break
    turn = turn + 1


if(all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:

if __name__ == '__main__':
    n, m = tuple(map(int, input().split()))
    d = {0: [1]}
    d.clear()
    d2 = {1: 0}
    l = [1]

    for i in range(0, m):
        t1, t2 = tuple(map(int, input().split()))
        if t1 in d.keys():
            d[t1].append(t2)
        else:
            d[t1] = [t2, ]
        if t2 in d.keys():
            d[t2].append(t1)
        else:
            d[t2] = [t1, ]
    j = 0
    for i in l:
        l += list(filter(lambda a: not (a in l), d[i]))
        d2[i] = j
        j += 1
    res = list(map(lambda a : min(map(lambda b : d2.get(b, -1),d[a])),range(2, n+1)))
    if -1 in res:
        print("No")
    else:
        print("Yes")
        for i in map(lambda a : l[a], res):
            print(i)






##    if len(d) < n:
##        print("No")
##    else:
##        print("Yes")
##        for i in range(2, n + 1):
##            print(d2[i])

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
from pprint import pprint

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)

room_next = [[] for n in range(N)]

for a, b in zip(A, B):
    room_next[a - 1].append(b - 1)
    room_next[b - 1].append(a - 1)

room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

stack = [0]
visited = []

while stack:
    # print('visited', visited)
    # print('next', stack)
    now = stack.pop()
    if now not in visited:
        visited.append(now)
        for r in room_next[now]:
            if room_depth[r] is None or room_depth[r] > room_depth[now] + 1:
                room_depth[r] = room_depth[now] + 1
                room_sign[r] = now + 1

                if r not in visited:
                    stack.append(r)

print('Yes')
for s in room_sign[1:]:
    print(s)

Submission status: Time Limit Exceeded

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

routes = []
for i in range(m):
    x,y = map(int, input().split())
    routes.append([x-1,y-1])
    # routes[i] = routes[i] - [1,1] #道の番号をずらす

rooms = [0 for i in range(n)] # 行ったら1,まだなら0
marks = [0 for i in range(n)] # 部屋におく道標
rooms_rate = [[0]] # １回目、２回目、３回目…に行ける部屋
rooms[0] = 1

turn = 0
for i in rooms_rate:
    newrate = []
    for j in rooms_rate[turn]: #turn回目に行ける部屋を調べる
        for k in range(m):
            a = routes[k][0]
            b = routes[k][1]
            if (j == a and rooms[b] == 0):
                rooms[b] = 1
                marks[b] = a
                newrate.append(b)
            elif (j == b and rooms[a] == 0):
                rooms[a] = 1
                marks[a] = b
                newrate.append(a)
    rooms_rate.append(newrate)
    if (len(newrate) == 0):
        break
    turn = turn + 1


if(all(rooms) == True):
    print('Yes')
    for i in range(1,n):
        print(str(int(marks[i]) + 1))

else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
from pprint import pprint

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)

room_next = [[] for n in range(N)]

for a, b in zip(A, B):
    room_next[a - 1].append(b - 1)
    room_next[b - 1].append(a - 1)

room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

stack = [0]
visited = []

while stack:
    now = stack.pop()
    if now not in visited:
        visited.append(now)
        for r in room_next[now]:
            if room_depth[r] is None or room_depth[r] > room_depth[now] + 1:
                room_depth[r] = room_depth[now] + 1
                room_sign[r] = now + 1
                stack.append(r)

print('Yes')
for s in room_sign[1:]:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append([a,b])

# program
Edict = [[] for n in range(N+1)]
for e in E:
    Edict[e[0]].append(e[1])
    Edict[e[1]].append(e[0])

output = [0] + [0] + [BigM]*(N-1)
prev = set([])
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    prev.add(n)
    elist = []
    for next in Edict[n]:
        if next not in now:
            if next not in prev:
                output[next] = n
                now.append(next)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
print("Yes")
N, M = map(int, input().split())
path = [[] for _ in range(N)]
ind = [0 for _ in range(N)]
lis = set()
for o in range(N):
    lis.add(o)
for i in range(M):
    A, B = map(int, input().split())
    path[A-1].append(B-1)
    path[B-1].append(A-1)
que = path[0]
for p in que:
    lis.discard(p)
for l in que:
    U = lis & set(path[l])
    for m in U:
        ind[m] = l
        lis.discard(m)
    que.extend(list(U))
    if lis == {}:
        break
for z in range(1,N):
    ind[z] += 1
    print(ind[z])

Submission status: Time Limit Exceeded

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append(set([a,b]))

# program
output = [0] + [0] + [BigM]*(N-1)
prev = set([])
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    prev.add(n)
    elist = []
    for e in E:
        if n in e:
            elist.append(e)
    for e in elist:
        next = list(e - set([n]))[0]
        if next not in now:
            if next not in prev:
                output[next] = n
                now.append(next)
        E.remove(e)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
# BFS

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)

# 接続している部屋のマップ
room_next = [[] for n in range(N)]

for a, b in zip(A, B):
    room_next[a - 1].append(b - 1)
    room_next[b - 1].append(a - 1)

room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

stack = [0]
visited = []

while stack:
    now = stack.pop()

    if now in visited:
        continue

    # print('now=', now)
    visited.append(now)
    for r in room_next[now]:
        if r not in visited:
            stack.append(r)

        if room_depth[r] is None:
            room_depth[r] = room_depth[now] + 1
            room_sign[r] = now + 1

print('Yes')
for s in room_sign[1:]:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
inp = input()
inp = inp.split()
N = int(inp[0])
M = int(inp[1])
BigM = N+2

E = []
for m in range(M):
    abinp = input()
    abinp = abinp.split()
    a = int(abinp[0])
    b = int(abinp[1])
    E.append(set([a,b]))

output = [0] + [0] + [BigM]*(N-1)
prev = set([])
prev_cnt = 0
now = [1]

while len(now) > 0:
    n = now.pop(0)
    prev_cnt += 1
    prev.add(n)
    elist = []
    for e in E:
        if n in e:
            elist.append(e)
    for e in elist:
        next = list(e - set([n]))[0]
        if next not in now:
            if next not in prev:
                output[next] = n
                now.append(next)
                E.remove(e)

if prev_cnt == N:
    print("Yes")
    for n in range(2,N+1):
        print(output[n])
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
# https://atcoder.jp/contests/abc168/tasks/abc168_d
# BFS

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)

# 接続している部屋のマップ
room_next = [[] for n in range(N)]

for a, b in zip(A, B):
    room_next[a - 1].append(b - 1)
    room_next[b - 1].append(a - 1)

room_depth = [None] * N
room_depth[0] = 0
room_sign = [None] * N

stack = [0]
visited = []

while stack:
    now = stack.pop()
    visited.append(now)
    for r in room_next[now]:
        if r not in visited:
            stack.append(r)

        if room_depth[r] is None:
            room_depth[r] = room_depth[now] + 1
            room_sign[r] = now + 1

print('Yes')
for s in room_sign[1:]:
    print(s)