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 sys
import copy
from io import StringIO
import unittest
from collections import deque

# 参考：https://atcoder.jp/contests/abc168/submissions/13401646

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

    # 各部屋のつながりを整理整頓する(添え字0は使わないので、+1して一つ多い配列を作成)
    roots = [[] for i in range(n + 1)]
    for i in ms:
        roots[i[0]].append(i[1])
        roots[i[1]].append(i[0])

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [99999 for i in range(n + 1)]
    aaa = [False for i in range(n + 1)]

    best_signs = [0 for i in range(n+1)]

    # 調べ終えた道を格納するタプル
    # searched = []

    # 初期値を代入
    que = deque()
    que.append(1)  # スタート地点
    deeps[1] = 0  # スタート地点の深さは0

    # BFS開始
    while not len(que) is 0:

        now = que.popleft()

        # 無限ループ防止のため調査済みフラグを立てる
        # searched.append(now)

        # 最適解を代入し続けて、適切な深さを求める
        for target in roots[now]:
            # 調査済みの道には何もしない。
            if aaa[target] is True:
                continue

            # 新しい道の場合。最適解を取得+キュー追加
            deeps[target] = deeps[now] + 1
            que.append(target)
            aaa[target] = True
            # 最適な道しるべを設定
            best_signs[target] = now

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    del best_signs[0:2]

    ans = "Yes"
    for best_sign in best_signs:
        ans = ans + "\n" + str(best_sign)

    print(ans)


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

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

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


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

Submission status: Time Limit Exceeded

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

# 参考：https://atcoder.jp/contests/abc168/submissions/13401646

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

    # 各部屋のつながりを整理整頓する(添え字0は使わないので、+1して一つ多い配列を作成)
    roots = [[] for i in range(n + 1)]
    for i in ms:
        roots[i[0]].append(i[1])
        roots[i[1]].append(i[0])

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [99999 for i in range(n + 1)]

    best_signs = [0 for i in range(n+1)]

    # 調べ終えた道を格納するタプル
    # searched = []

    # 初期値を代入
    que = deque()
    que.append(1)  # スタート地点
    deeps[1] = 0  # スタート地点の深さは0

    # BFS開始
    while not len(que) is 0:

        now = que.popleft()

        # 無限ループ防止のため調査済みフラグを立てる
        # searched.append(now)

        # 最適解を代入し続けて、適切な深さを求める
        for target in roots[now]:
            # 調査済みの道には何もしない。
            if deeps[target] is not 99999:
                continue

            # 新しい道の場合。最適解を取得+キュー追加
            deeps[target] = deeps[now] + 1
            que.append(target)
            # 最適な道しるべを設定
            best_signs[target] = now

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    del best_signs[0:2]

    ans = "Yes"
    for best_sign in best_signs:
        ans = ans + "\n" + str(best_sign)

    print(ans)


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

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

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


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

Submission status: Time Limit Exceeded

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

# 参考：https://atcoder.jp/contests/abc168/submissions/13401646

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

    # 各部屋のつながりを整理整頓する(添え字0は使わないので、+1して一つ多い配列を作成)
    roots = [[] for i in range(n + 1)]
    for i in ms:
        roots[i[0]].append(i[1])
        roots[i[1]].append(i[0])

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [99999 for i in range(n + 1)]

    # 調べ終えた道を格納するタプル
    searched = []

    # 初期値を代入
    que = deque()
    que.append(1)  # スタート地点
    deeps[1] = 0  # スタート地点の深さは0

    # BFS開始
    while not len(que) is 0:

        now = que.popleft()

        # 繋がる道全てを取得
        targets = roots[now]

        # 無限ループ防止のため調査済みフラグを立てる
        searched.append(now)

        # 最適解を代入し続けて、適切な深さを求める
        for target in targets:
            # 調査済みの道には何もしない。
            if target in searched:
                continue

            # 新しい道の場合。最適解を取得+キュー追加
            deeps[target] = min(deeps[target], deeps[now] + 1)
            que.append(target)

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    # del deeps[0:2]

    # 最適な道しるべの一覧を取得
    best_signs = []
    for i in range(2, len(deeps)):
        for j in roots[i]:
            if deeps[j] is deeps[i] - 1:
                best_signs.append(j)
                break

    ans = "Yes"
    for best_sign in best_signs:
        ans = ans + "\n" + str(best_sign)

    print(ans)


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

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

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


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

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
from io import StringIO
import unittest
import queue


# 参考：https://atcoder.jp/contests/abc168/submissions/13401646

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

    # 各部屋のつながりを整理整頓する(添え字0は使わないので、+1して一つ多い配列を作成)
    roots = [[] for i in range(n + 1)]
    for i in ms:
        roots[i[0]].append(i[1])
        roots[i[1]].append(i[0])

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [999999 for i in range(n + 1)]

    # 調べ終えた道を格納するタプル
    searched = []

    # 初期値を代入
    que = queue.Queue()
    que.put(1)  # スタート地点
    deeps[1] = 0  # スタート地点の深さは0

    # BFS開始
    while not que.empty():

        now = que.get()

        # 繋がる道全てを取得
        targets = roots[now]

        # 無限ループ防止のため調査済みフラグを立てる
        searched.append(now)

        # 最適解を代入し続けて、適切な深さを求める
        for target in targets:
            # 調査済みの道には何もしない。
            if target in searched:
                continue

            # 新しい道の場合。最適解を取得+キュー追加
            deeps[target] = min(deeps[target], deeps[now] + 1)
            que.put(target)

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    # del deeps[0:2]

    # 最適な道しるべの一覧を取得
    best_signs = []
    for i in range(2, len(deeps)):
        for j in roots[i]:
            if deeps[j] is deeps[i] - 1:
                best_signs.append(j)
                break

    ans = "Yes"
    for best_sign in best_signs:
        ans = ans + "\n" + str(best_sign)

    print(ans)


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

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

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


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

Submission status: Time Limit Exceeded

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

A=[]
B=[]

for _ in range(M):
  n, m = map(int, input().split())
  A.append(n)
  B.append(m)

roomN = ['N' for _ in range(N)]
roomN[0] = 1
roomPN = [0 for _ in range(N)]

for order in range(2, N+1):
  if not 'N' in roomN:
    break
  if order-1 in roomN:
     pres = [i+1 for i,x in enumerate(roomN) if x == order-1]
  for pre in pres:
    if pre in A:
      indexs = [i for i,x in enumerate(A) if x == pre]
      for index in indexs:
        now = B[index] -1
        if roomN[now] == 'N':
          roomN[now] = order
          if roomPN[now] == 0:
            roomPN[now] = pre
    if pre in B:
      indexs = [i for i,x in enumerate(B) if x == pre]
      for index in indexs:
        now = A[index] -1
        if roomN[now] == 'N':
          roomN[now] = order
          if roomPN[now] == 0:
            roomPN[now] = pre

print('Yes')
for i in range(1, N):
  print(roomPN[i])

Submission status: Time Limit Exceeded

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

A=[]
B=[]

for _ in range(M):
  n, m = map(int, input().split())
  A.append(n)
  B.append(m)

roomN = ['N' for _ in range(N)]
roomN[0] = 1
roomPN = [0 for _ in range(N)]

for order in range(2, N+1):
  if order-1 in roomN:
     pres = [i+1 for i,x in enumerate(roomN) if x == order-1]
  for pre in pres:
    if pre in A:
      indexs = [i for i,x in enumerate(A) if x == pre]
      for index in indexs:
        now = B[index] -1
        if roomN[now] == 'N':
          roomN[now] = order
          if roomPN[now] == 0:
            roomPN[now] = pre
    if pre in B:
      indexs = [i for i,x in enumerate(B) if x == pre]
      for index in indexs:
        now = A[index] -1
        if roomN[now] == 'N':
          roomN[now] = order
          if roomPN[now] == 0:
            roomPN[now] = pre

print('Yes')
for i in range(1, N):
  print(roomPN[i])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
N, M = map(int, input().split())

edge_list = s = [input().split() for i in range(M)]
G = nx.Graph()
G.add_edges_from(edge_list)

if [] in nx.shortest_path(G, target=str(1)).values():
  print("No")
else:
  print("Yes")
  for i in range(len(list(nx.shortest_path(G, target=str(1)).values()))-1):
    print(nx.shortest_path(G, target=str(1))[str(i+2)][1])

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
N, M = map(int, input().split())

edge_list = s = [input().split() for i in range(M)]
G = nx.Graph()
G.add_edges_from(edge_list)

if [] not in nx.shortest_path(G, target=str(1)).values():
    print("Yes")
    for i in range(2,N+1):
      print(nx.shortest_path(G, source=str(i), target=str(1))[1])
else:
    print("No")

Submission status: Time Limit Exceeded

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

s=[-1]*N
d=[-1]*N

s[0]=0
d[0]=0


for i in range(N):
  finish=1
  for j in range(N):
    if d[j]==i:
      for saki in graph[j]:
        if d[saki]==-1:
          d[saki]=i+1
          s[saki]=j
          finish=0
  if finish==1:
    break

print("Yes")
for i in range(N-1):
  print(s[i+1]+1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import maxsize
from copy import deepcopy


class Graph:
    def __init__(self, No_of_nodes):
        self.n = No_of_nodes
        self.adj = [[] for i in range(self.n)]

    def addEdge(self, a, b, w):
        self.adj[a].append([b, w])

    def dijkstra(self, start):
        nxtpoint = [None for i in range(self.n)]
        distance = [maxsize for i in range(self.n)]
        distance[start] = 0
        q = deque()
        q.append(start)
        while len(q) != 0:
            a = q.pop()
            for u in self.adj[a]:
                b, w = u
                if distance[a] + w < distance[b]:
                    distance[b] = distance[a] + w
                    nxtpoint[b] = a
                    q.append(b)
        return nxtpoint


n, m = map(int, input().split())
ls = []
g = Graph(n)
ans = 'Yes\n'
for i in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    g.addEdge(a, b, 1)
    g.addEdge(b, a, 1)
point = g.dijkstra(0)
for i in range(1,n):
    if point[i] is None:
        ans = 'No'
        break
    else:
        ans += str(point[i] + 1) +'\n'
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M = map(int, input().split())
AB_s = [list(map(int, input().split())) for _ in range(M)]

answer = [0] * N
queue = deque([1])
answer[0] = N

while len(queue) > 0:
    P = queue.popleft()
    POPS = []
    for i, AB in enumerate(AB_s):
        # P の含まれるパスだったら
        if P in AB:
            # P じゃない方が Q
            Q = AB[0] if AB[1] == P else AB[1]
            # 到達してなかったら道標を置く
            if answer[Q-1] == 0:
                answer[Q-1] = P
                queue.append(Q)
            POPS.append(i)
    for POP in POPS[::-1]:
        AB_s.pop(POP)

if min(answer) == 0:
    print("No")
else:
    print("Yes")
    for i in range(1,N):
        print(answer[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M = map(int, input().split())
AB_s = sorted([sorted(list(map(int, input().split()))) for _ in range(M)])

answer = [0] * N
queue = deque([1])
answer[0] = N

while len(queue) > 0:
    P = queue.popleft()
    POPS = []
    for i, AB in enumerate(AB_s):
        # P の含まれるパスだったら
        if P in AB:
            # P じゃない方が Q
            Q = AB[0] if AB[1] == P else AB[1]
            # 到達してなかったら道標を置く
            if answer[Q-1] == 0:
                answer[Q-1] = P
                queue.append(Q)
            POPS.append(i)
    for i, POP in enumerate(POPS[::-1]):
        AB_s.pop(POP)

if min(answer) == 0:
    print("No")
else:
    print("Yes")
    for i in range(1,N):
        print(answer[i])

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int,input().split())
AB = [list(map(int, input().split())) for _ in range(M)]
prev = [0] * N
to_list = [ [] for _ in range(N)]

for a,b in AB:
  to_list[a - 1].append(b - 1)
  to_list[b - 1].append(a - 1)

marked = [0]
stack = [0]

for i in stack:
    for j in to_list[i]:
        if j in marked: continue
        stack.append(j)
        marked.append(j)
        prev[j] = i+1

print('Yes')
print(*prev[1:], sep='\n')

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int,input().split())
ab = [list(map(lambda s: int(s)-1, input().split()))for _ in range(M)]
prev = [0] * N
to_list = [[]for _ in range(N)]

for a,b in ab:
  to_list[a].append(b)
  to_list[b].append(a)

marked = [0]
stack = [0]

for i in stack:
    for j in to_list[i]:
        if j in marked: continue
        stack.append(j)
        marked.append(j)
        prev[j] = i

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

Submission status: Time Limit Exceeded

Solution code:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p = [[] for _ in range(n)]
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p[a-1].append(b)
    p[b-1].append(a)
d = [1, ]
con = [0] * n
l = 0
while d:
    for i, k in enumerate(p[1:]):
        if con[i]!=0:continue
        if d[0] in k:
            d.append(i+2)
            con[i] = d[l]
    if len(d) > 1:
        d.pop(0)
    else:
        break
print('Yes')
for i in range(n-1):
    print(con[i])

Submission status: Time Limit Exceeded

Solution code:
it = input()
it = it.split()
n = int(it[0])
m = int(it[1])
p = [[] for _ in range(n)]
for _ in range(m):
    itf = input()
    itf = itf.split()
    a = int(itf[0])
    b = int(itf[1])
    p[a-1].append(b)
    p[b-1].append(a)
d = [1, ]
con = [0] * n
l = 0
for _ in range(1, n):
    for i, k in enumerate(p[1:]):
        if con[i]!=0:continue
        if d[l] in k:
            d.append(i+2)
            con[i] = d[l]
    if len(d) > l:
        l += 1
    else:
        break
print('Yes')
for i in range(n-1):
    print(con[i])

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy
from io import StringIO
import unittest
import queue

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


    que = queue.Queue()

    # 各部屋の深さを保持する配列を作成(配列は0始まりだが、番号は1始まりなので+1(添え字0は使用しない想定))
    deeps = [999999 for i in range(n+1)]

    best_signs = [0 for i in range(n+1)]

    # 調べ終えた道を格納するリスト
    searched = []

    # 初期値を代入
    que.put(1)  # スタート地点
    deeps[1] = 0 # スタート地点の深さは0

    # BFS開始
    while not que.empty():

        now = que.get()

        # 繋がる道を全て確認
        for root in roots:
            # 現在地と繋がらない道の場合・・何もしない
            if now not in root:
                continue

            # 調査済みの道の場合・・何もしない
            if str(root[0]) + "-" + str(root[1]) in searched:
                continue

            # 現在地と繋がる道の場合・・
            # [前処理]
            # 自分の座標を削除 = これで、繋がり先だけを保持した変数を作れる。
            work = copy.deepcopy(root)
            work.remove(now)
            target = work[0]

            # 調査済みリストに追加
            searched.append(str(root[0]) + "-" + str(root[1]))

            # [主処理]
            # queに追加
            que.put(target)

            # 見つけた組み合わせが最適解の場合
            if deeps[target] > deeps[now]+1:
                # 最適解を採用
                deeps[target] = deeps[now]+1
                best_signs[target] = now
            # 最小の深さを採用
            # deeps[target] = min(deeps[target], deeps[now] + 1)

    # 不要な添え字を削除(0番目=未使用なので不要 1番目=出力しないので不要)
    del best_signs[0:2]

    ans = "Yes"
    for best_sign in best_signs:
        ans = ans + "\n" + str(best_sign)

    print(ans)



class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """4 4
1 2
2 3
3 4
4 2"""
        output = """Yes
1
2
2"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6"""
        output = """Yes
6
5
5
1
1"""
        self.assertIO(input, output)

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

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx

N,M = map(int,input().split())
G = nx.Graph()
for i in range(M):
    A,B = map(int,input().split())
    G.add_edge(A,B)
print("Yes")
for i in range(2,N+1):
    pre = nx.predecessor(G,1)
    print(pre[i][0])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M=map(int,input().split())
ab=[list(map(int,input().split())) for i in range(M)]
l=[0]*N
que=deque([])
que.append(1)
def bfs():
  while que:
     if 0 not in l:
         exit()
     p=que.popleft
     for i in range(M):
          if ab[i][0]==p:
            que.append(ab[i][1])
            l[ab[i][1]-1]=p
          if ab[i][1]==p:
             que.append(ab[i][0])
             l[ab[i][0]-1]=p
  print("Yes")
  print(*l) 
bfs()

Submission status: Time Limit Exceeded

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

list = [0] * (N+1)

saitan = [1]
for _ in range(M):
    next = []
    for i in range(len(AB)):
        if AB[i][0] in saitan:
            if list[AB[i][1]] == 0:
                list[AB[i][1]] = AB[i][0]
                next.append(AB[i][1])
        if AB[i][1] in saitan:
            if list[AB[i][0]] == 0:
                list[AB[i][0]] = AB[i][1]
                next.append(AB[i][0])
    saitan.extend(next)


print("Yes")
for ele in list[2:]:
    print(ele)

Submission status: Time Limit Exceeded

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

p = [0] * (n+1)
a = [0] * m
b = [0] * m


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

s=list()
t=list()
t.append(1)


while(1):
    for j in t:
        for k in range(m):
            if a[k]==j and p[b[k]] == 0:
                p[b[k]]=a[k]
                s.append(b[k])

            if b[k]==j and p[a[k]]==0:
                p[a[k]]=b[k]
                s.append(a[k])
                

    if len(s)==0:
        break
    else:
        t = s
        s = []
    
if 0 in p[2:]:
    print('No')
else:
    print('Yes')
    for q in p[2:]:
        print(q)

Submission status: Time Limit Exceeded

Solution code:
import networkx

n, m = map(int, input().split())
g = networkx.Graph()
g.add_nodes_from(list(range(n)))
for i in range(1, m + 1):
    a, b = map(int, input().split())
    g.add_edge(a, b)
#print(g.nodes())
#print(g.edges())
print("Yes")
for i in range(2, n + 1):
    print(networkx.shortest_path(g, 1, i)[-2])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m = map(int,input().split())

p = [0] * (n+1)
a = [0] * m
b = [0] * m


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

s=list()
t=list()
t.append(1)

while(1):
    for j in t:
        for k in range(m):

            if a[k]==j and p[b[k]] == 0:
                p[b[k]]=a[k]
                s.append(b[k])

            if b[k]==j and p[a[k]]==0:
                p[a[k]]=b[k]
                s.append(a[k])

    if len(s)==0:
        break
    else:
        t = s
        s = []
    
if 0 in p[2:]:
    print('No')
else:
    print('Yes')
    for q in p[2:]:
        print(q)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N,M = map(int, input().split())
root = []
for i in range(M):
  tmp = list(map(int, input().split()))
  root.append(tmp)

visited = np.zeros(N)
Q = []				# キューを格納するための箱
visited[0] = 1		# 訪問済み
Q.append(1)			# 探索する要素を追加
while 1:
  q = Q.pop(0)
  for i in range(M):
    if (q in root[i] and visited[root[i][0]-1] == 0) or (q in root[i] and visited[root[i][1]-1] == 0):
      if root[i][0] == q:	
        visited[root[i][1]-1] = q
        Q.append(root[i][1])
      elif root[i][1] == q:	
        visited[root[i][0]-1] = q
        Q.append(root[i][0])
  #print(Q)
  if len(Q) == 0:
    break
if sum(visited) != 1:
  print('Yes')
  for i in range(1,N,1):
    print(int(visited[i]))
else:
  print('No')

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m = map(int,input().split())

p = [0] * (n+1)
s = [0] * (n+1)

s[1]=1

a = [0] * m
b = [0] * m


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

for i in range(1,n+1):
    t=False
    for j in range(1,n+1):
        if s[j] == i:
            for k in range(m):
                if a[k]==j and p[b[k]] == 0:
                    p[b[k]]=a[k]
                    s[b[k]]=i+1
                    t=True

                if b[k]==j and p[a[k]]==0:
                    p[a[k]]=b[k]
                    s[a[k]]=i+1
                    t=True
    if t==False:
        break
    
if 0 in p[2:]:
    print('No')
else:
    print('Yes')
    for q in p[2:]:
        print(q)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m = map(int,input().split())

p = np.zeros(n+1,dtype=int)
s = np.zeros(n+1,dtype=int)

s[1]=1

a = np.zeros(m,dtype=int)
b = np.zeros(m,dtype=int)


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

for i in range(1,n+1):
    t=False
    for j in range(1,n+1):
        if s[j] == i:
            for k in range(m):
                if a[k]==j and p[b[k]] == 0:
                    p[b[k]]=a[k]
                    s[b[k]]=i+1
                    t=True

                if b[k]==j and p[a[k]]==0:
                    p[a[k]]=b[k]
                    s[a[k]]=i+1
                    t=True
    if t==False:
        break
    
if 0 in p[2:]:
    print('No')
else:
    print('Yes')
    for q in p[2:]:
        print(q)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
l = []
v = [-1]*N
v_old = v[:]
v[0] = 0
ans = v[:]
#print(v_old)
#print(v)
for i in range(M):
  a, b = list(map(int, input().strip().split()))
  if a > b:
    c = a
    a = b
    b = c
  l.append([a, b])
  #print(a, b)
l.sort()

count = 0
flag = 1
while flag == 1:
  flag = 0
  #print(count)
  count = count + 1
  for i in range(M):
    room_1 = l[i][0] -1
    room_2 = l[i][1] -1
    #print('room')
    #print(room_1, room_2)
    if v[room_1] == -1 and v[room_2] == -1:
      pass
    elif v[room_1] == -1:
      flag = 1
      v[room_1] = v[room_2] + 1
      ans[room_1] = room_2 + 1
    elif v[room_2] == -1:
      flag = 1
      v[room_2] = v[room_1] + 1
      ans[room_2] = room_1 + 1  
    elif v[room_1] + 1 < v[room_2]:
      flag = 1
      v[room_2] = v[room_1] + 1
      ans[room_2] = room_1 + 1
    elif v[room_1] > v[room_2] + 1:
      flag = 1
      v[room_1] = v[room_2] + 1
      ans[room_1] = room_2 + 1
    #print(v)
    #print(v_old)
#print(l)
#print(v)
#print(ans)
print('Yes')
for i in ans:
  if i != 0:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
l = []
v = [-1]*N
v_old = v[:]
v[0] = 0
ans = v[:]
#print(v_old)
#print(v)
for i in range(M):
  a, b = list(map(int, input().strip().split()))
  if a > b:
    c = a
    a = b
    b = c
  l.append([a, b])
  #print(a, b)
l.sort()

count = 0
while v != v_old:
  v_old = v[:]
  #print(count)
  count = count + 1
  for i in range(M):
    room_1 = l[i][0] -1
    room_2 = l[i][1] -1
    #print('room')
    #print(room_1, room_2)
    if v[room_1] == -1 and v[room_2] == -1:
      pass
    elif v[room_1] == -1:
      v[room_1] = v[room_2] + 1
      ans[room_1] = room_2 + 1
    elif v[room_2] == -1:
      v[room_2] = v[room_1] + 1
      ans[room_2] = room_1 + 1  
    elif v[room_1] < v[room_2]:
      v[room_2] = v[room_1] + 1
      ans[room_2] = room_1 + 1
    elif v[room_1] > v[room_2]:
      v[room_1] = v[room_2] + 1
      ans[room_1] = room_2 + 1
    #print(v)
    #print(v_old)
#print(l)
#print(v)
#print(ans)
print('Yes')
for i in ans:
  if i != 0:
    print(i)

Submission status: Time Limit Exceeded

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

ans_list = [0] * (N+1)

dq = collections.deque()

dq.append(1)

print("Yes")
for hoge in range(500000):
    i = dq.popleft()
    iList = [temp for temp in ABs if i in temp]

    iList = list(itertools.chain.from_iterable(iList))
    iList = [temp for temp in iList if iList !=i]

    for hoge in iList:
        if(ans_list[hoge] == 0):
            ans_list[hoge] = i
            dq.append(hoge)


    if(len(dq) == 0):
        break

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

Submission status: Time Limit Exceeded

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

ans_list = [0] * (N+1)

dq = collections.deque()

dq.append(1)

print("Yes")
for hoge in range(500000):
    i = dq.popleft()
    iList = [temp for temp in ABs if i in temp]

    iList = list(itertools.chain.from_iterable(iList))
    iList = [temp for temp in iList if iList !=i]

    for hoge in iList:
        if(ans_list[hoge] == 0):
            ans_list[hoge] = i
        dq.append(hoge)

    if(0 not in ans_list[2:]):
        break

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

Submission status: Time Limit Exceeded

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

ans_list = [0] * (N+1)

dq = collections.deque()

dq.append(1)

print("Yes")
while 0 in ans_list[2:]:
    i = dq.popleft()
    iList = [temp for temp in ABs if i in temp]

    iList = list(itertools.chain.from_iterable(iList))
    iList = [temp for temp in iList if iList !=i]

    for hoge in iList:
        if(ans_list[hoge] == 0):
            ans_list[hoge] = i
        dq.append(hoge)

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

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

d = defaultdict(list)

for i in xrange(m):
    (a, b) = map(int, raw_input().split())
    d[a].append(b)
    d[b].append(a)

pre = [0 for i in xrange(n + 1)]
cnt = 0

q = [1]
while q:
    cur = q.pop(0)
    for nxt in d[cur]:
        if pre[nxt] == 0:
            cnt += 1
            pre[nxt] = cur
            q.append(nxt)


if cnt < n - 1:
    print 'No'
else:
    print 'Yes'
    for i in xrange(2, n + 1):
        print pre[i]