Problem:


Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 2 \times 10^5

1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.



Sample input:
4 4
1 2
2 3
3 4
4 2


Sample output:
Yes
1
2
2

Submission status: Wrong Answer

Solution code:
from collections import deque


N,M = (int(x) for x in input().split())
connected = [[] for _ in range(N+1)]
searched = [0] * (N+1)
signs = [0] * (N+1)
for i in range(M):
    A,B = (int(x) for x in input().split())
    connected[A].append(B)
    connected[B].append(A)
d = deque()
for edge in connected[1]:
    d.append(edge)
    signs[edge] = 1
searched[1] = 1
while d:
    temp = d.popleft()
    for edge in connected[temp]:
        if searched[edge] == 0:
            d.append(edge)
            signs[edge] = temp
            searched[edge] = 1
    searched[temp] = 1
print('Yes')
for x in signs[2:]:
    print(x)

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
X = [[] for x in range(N+1)]
for m in range(M):
    A, B = map(int, input().split())
    X[A].append(B)
    X[B].append(A)

Q = deque()
Q.append(1)

D = [-1]*(N+1)
D[0] = 0
D[1] = 0
while Q:
    v = Q.pop()
    for i in X[v]:
        if D[i] == -1:
            D[i] = i
            Q.appendleft(i)
if -1 in D:
    print('No')
else:
    print('Yes')
    print(*D[2:])

Submission status: Wrong Answer

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

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

Pas=[0 for i in range(N+1)]
Flag=[True for i in range(N+1)]
st=[1]
cnt=0
while len(st):
    cnt+=1
    s=st.pop()
    for i in X[s]:
        if Flag[i]:
            Pas[i]=s
            Flag[i]=False
            st.append(i)

result="Yes"
for i in range(2,N+1):
    if Flag[i]:
        result="No"

if result=="Yes":
    print(result)
    for i in range(2,N+1):
        print(Pas[i])
else:
    print(result)

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
X = [[] for x in range(N+1)]
for m in range(M):
    A, B = map(int, input().split())
    X[A].append(B)
    X[B].append(A)

Q = deque()
Q.append(1)

D = [-1]*(N+1)
D[0] = 0
D[1] = 0
while Q:
    v = Q.pop()
    for i in X[v]:
        if D[i] == -1:
            D[i] = 1
            Q.appendleft(i)
if -1 in D:
    print('No')
else:
    print('Yes')
    for i in range(2,len(D)):
        print(D[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M = map(int, input().split())
X = [[] for x in range(N+1)]
for m in range(M):
    A, B = map(int, input().split())
    X[A].append(B)
    X[B].append(A)

Q = deque()
Q.append(1)

D = [-1]*(N+1)
D[0] = 0
D[1] = 0
while Q:
    v = Q.pop()
    for i in X[v]:
        if D[i] == -1:
            D[i] = D[v] + 1
            Q.appendleft(i)
if -1 in D:
    print('No')
else:
    print('Yes')
    for i in range(2,len(D)):
        print(D[i])

Submission status: Wrong Answer

Solution code:
import queue

n,m = map(int,input().split())
hen = [[] for i in range(100000)]
ans = [0 for i in range(100000)]
count = 1
a,b = 0,0
max = 0

for i in range(m):
    a,b = map(int,input().split())
    hen[a-1].append(b)
    hen[b-1].append(a)
    if b > max:
        max = b
    else:
        max = a

q = queue.Queue()
q.put(1)

while q.empty() == False:
    head = q.get()
    for h in hen[head-1]:
        if h != 1 and ans[h-1] == 0:
            ans[h-1] = head
            count += 1
            q.put(h)

if count == max:
    print('Yes')
    for i in range(max-1):
        print(ans[i+1])
else:
    print('No')

Submission status: Wrong Answer

Solution code:
from queue import Queue

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

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

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


placas = [0] * (n)

def bfs(a):
    q = Queue(maxsize = n)
    placas[1] = 1
    q.put(a)
    while not q.empty():
        popado = q.get()
        for adj in grafo[popado-1]:
            if not placas[adj-1]:
                placas[adj-1] = popado
                q.put(adj)

    if placas.count(0) == 0:
        print("Yes")
        for x in placas[1::]:
            print(x)
    else:
        print("No")

bfs(1)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

q = deque()
q.append(1)

mark = [None for _ in range(n+1)]
mark[0] = 0

for _ in range(n):
    
    i = q.popleft()
    
    for j in range(len(adj[i])):
        q.append(adj[i][j])
        
        if mark[adj[i][j]] == None:
            mark[adj[i][j]] = i

if None in mark:
    print('No')
else:
    print('Yes')
    for i in range(2, len(mark)):
        print(mark[i])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections import defaultdict
sys.setrecursionlimit(10**8)
INF = float("inf")
import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):

    c = np.ones(M)
    edge = csr_matrix((c, (A, B)), (N+1, N+1))
    forward_dist, pred = dijkstra(
        edge, indices=1, return_predecessors=True, directed=False)

    if (pred[2:] == -9999).any():
        print("No")
    else:
        print("Yes")
        for value in pred[2:]:
            print(value)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections import defaultdict
sys.setrecursionlimit(10**8)
INF = float("inf")
import numpy as np
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):

    # cは重み配列、a, bは始点のリストと終点のリスト
    c = np.ones(M)
    edge = csr_matrix((c, (A, B)), (N+1, N+1))
    forward_dist, pred = dijkstra(
        edge, indices=1, return_predecessors=True, directed=False)
    ans = []
    for i in range(2, N+1):
        if pred[i] == -9999:
            print("No")
            return
        ans.append(str(pred[i]))
    print("Yes")
    print("\n".join(ans))
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
G = [[] for _ in range(n+1)]
dep = [0] * (n+1)

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

visited = [-1] * (n+1)
q = deque()
q.append(1)
while q:
    now = q.popleft()
    #print("now:",now)
    visited[now] = 1
    for next in G[now]:
        #print(next)
        if visited[next] == -1:
            q.append(next)
            dep[next] = dep[now] + 1
            visited[next] = 1
print("Yes")
print("\n".join(map(str,dep[2:])))

Submission status: Wrong Answer

Solution code:
import math
import sys

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

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

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

# 実装

ans = [-1] * n


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


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


print("Yes")
ans.pop(0)
for i in ans:
    print(i)

Submission status: Wrong Answer

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

root = [[] for i in range(n)]
for _ in range(m):
    a, b = (int(x) for x in input().split())
    root[b-1].append(a-1)
    root[a-1].append(b-1) 

stack=[0]
check = [-1]*n
check[0] = 0

while len(stack)>0:
    v = stack.pop()
    for i in root[v]:
        if check[i] == -1:
            check[i]=v+1
            stack.append(i)


print('Yes')
for i in range(1,n):
    print(check[i])

Submission status: Wrong Answer

Solution code:

N, M = map(int, input().split())
AB = [list(map(int, input().split())) for i in range(M)]
P = [0] * N
n = N - 1
q = [1]
j = 0
while n > 0:
    for i in range(M):
        if AB[i][0] == q[j]:
            if P[AB[i][1] - 1] == 0:
                P[AB[i][1] - 1] = q[j]
                q.append(AB[i][1])               
                AB[i] = [0, 0]
                n -= 1
        elif AB[i][1] == q[j]:
            if P[AB[i][0] - 1] == 0:
                P[AB[i][0] - 1] = q[j]
                q.append(AB[i][0])
                AB[i] = [0, 0]               
                n -= 1
    j += 1
print('Yes')
for i in range(1, N):
    print(P[i])

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
room = []
ans = []
for i in range(1,n):
  room.append([i,i])
  ans.append(0)
room.append([n,n])
ab = []
for i in range(m):
  a,b = map(int,input().split())
  ab.append([min(a,b)-1,max(a,b)-1])
ab.sort()
for i in range(len(ab)):
  if(room[ab[i][0]][1]==1):
    ans[ab[i][1]-1]=room[ab[i][0]][0]
    room[ab[i][1]][1]=1
judge = 0
for i in range(n):
  if(room[i][1]==1):
    None
  else:
    judge = 1
    break
if(judge==0):
  print("Yes")
  for i in range(len(ans)):
    print(ans[i])
else:
  print("No")

Submission status: Wrong Answer

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

root = [[] for i in range(n)]
for _ in range(m):
    a, b = (int(x) for x in input().split())
    root[b-1].append(a-1)
    root[a-1].append(b-1) 

stack=[0]
check = [-1]*n
check[0] = 0

while len(stack)>0:
    v = stack.pop(0)
    for i in root[v]:
        if check[i] == -1:
            check[i]=check[v]+1
            stack.append(i)

if -1 in check:
    print('No')
else:
    print('Yes')
    for i in range(1,n):
        print(check[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M = map(int,input().split())

root = [set()for i in range(N+1)]
ans = [0 for i in range(N+1)]

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

task = deque([1])
itta = {1}
kai = 1 

while len(task) > 0:
    now = task.popleft()
    additionanl = root[now] - itta #到達済みを排除している
    for i in additionanl: #ノードチェック
        ans[i] = kai 
        itta.add(i)
    task.extend(list(additionanl)) #チェックしたノードを追加
    kai+=1
print("Yes")
for i in range(2,N+1):
    print(ans[i])

Submission status: Wrong Answer

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

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



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

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

from collections import deque

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

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

    return nodes, nodeStates, prevs


nodes, nodeStates, prevs = prepare(N, M, ARR)


def bfs(nodes, nodeStates, prevs, n):
    q = deque()
    q.append({'prev': -1, 'to': 0})
    while len(q) > 0:
        first = q.popleft()
        currentNode = first['to']
        previousNode = first['prev']
        if nodeStates[currentNode] != -1:
            continue
        prevs[currentNode] = previousNode
        childNodes = nodes[currentNode]
        nodeStates[currentNode] = 1
        for childNode in childNodes:
            q.append({'prev': currentNode, 'to': childNode})

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


bfs(nodes, nodeStates, prevs, N)

Submission status: Wrong Answer

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

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



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

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

from collections import deque

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

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

    return nodes, nodeStates, prevs


nodes, nodeStates, prevs = prepare(N, M, ARR)


def bfs(nodes, nodeStates, prevs, n):
    q = deque()
    q.append({'prev': -1, 'to': 0})
    while len(q) > 0:
        first = q.popleft()
        currentNode = first['to']
        previousNode = first['prev']
        if nodeStates[currentNode] != -1:
            continue
        prevs[currentNode] = previousNode
        childNodes = nodes[currentNode]
        nodeStates[currentNode] = 1
        for childNode in childNodes:
            q.append({'prev': currentNode, 'to': childNode})

    for i in range(1,n):
        print(prevs[i])


bfs(nodes, nodeStates, prevs, N)

Submission status: Wrong Answer

Solution code:
import heapq
from collections import deque
class Graph:
    def __init__(self,v,edgelist,w_v = None,directed = False):
        super().__init__()
        self.v = v
        self.w_e = [{} for _ in [0]*self.v]
        self.neighbor = [[] for _ in [0]*self.v]
        self.w_v = w_v
        self.directed = directed

        for i,j,w in edgelist:
            self.w_e[i][j] = w
            self.neighbor[i].append(j)

    def dijkstra(self,v_n):
        d = [float('inf')]*self.v
        d[v_n] = 0
        prev = [-1]*self.v

        queue = []
        for i,d_i in enumerate(d): heapq.heappush(queue,(d_i,i))
        
        while len(queue)>0:
            d_u,u = queue.pop()
            if d[u]<d_u :continue
            for v in self.neighbor[u]:
                alt = d[u]+self.w_e[u][v]
                if d[v]>alt:
                    d[v] = alt
                    prev[v] = u
                    heapq.heappush(queue,(alt,v))

        return d,prev

    def warshallFloyd(self):
        d = [[10**18]*self.v for _ in [0]*self.v]
        for i in range(self.v):
            d[i][i] = 0
            
        for i in range(self.v):
            for j in self.neighbor[i]:
                d[i][j] = self.w_e[i][j]
            
        for i in range(self.v):
            for j in self.neighbor[i]:
                d[i][j] = self.w_e[i][j]
        
        for k in range(self.v):
            for i in range(self.v):
                for j in range(self.v):
                    check = d[i][k] + d[k][j]
                    if d[i][j] > check:
                        d[i][j] = check
        return d

    def prim(self):
        gb = GraphBuilder(self.v,self.directed)

        queue = []
        for i,w in self.w_e[0].items(): heapq.heappush(queue,(w,0,i))
        rest = [True]*self.v
        rest[0] = False

        while len(queue)>0:
            w,i,j = heapq.heappop(queue)
            if rest[j]:
                gb.addEdge(i,j,w)
                rest[j] = False
                for k,w in self.w_e[j].items():
                    if rest[k]:
                        heapq.heappush(queue,(w,j,k))

        return gb

    def bfs(self,vartex = 0):
        todo = [True]*self.v
        queue = deque([vartex])
        while(len(queue)>0):
            v = queue.popleft
            todo[v] = False
            yield v
            for v_i in self.neighbor[v]:
                if todo[v_i]:
                    queue.append(v_i)

    def dfs(self,vartex = 0):
        seen = [False]*self.v
        def recdfs(v):
            seen[vartex] = True
            for next_v in self.neighbor[vartex]:
                if (seen[next_v]):continue
                recdfs(next_v)
            
class Tree():
    def __init__(self,v,e):
        pass

class GraphBuilder():
    def __init__(self,v,directed = False,edge = None, weights = None):
        self.v = v
        self.directed = directed
        self.edge = []
        self.weights = []
        if edge is not None:
            self.addEdges(edge)
        if weights is not None:
            self.addVartex(weights)

    def addEdge(self,i,j,w=1):
        if not self.directed:
            self.edge.append((j,i,w))
        self.edge.append((i,j,w))

    def addEdges(self,edgelist,weight = True):
        if weight:
            if self.directed:
                for i,j,w in edgelist:
                    self.edge.append((i,j,w))
            else:
                for i,j,w in edgelist:
                    self.edge.append((i,j,w))
                    self.edge.append((j,i,w))
        else:
            if self.directed:
                for i,j in edgelist:
                    self.edge.append((i,j,1))
            else:
                for i,j in edgelist:
                    self.edge.append((i,j,1))
                    self.edge.append((j,i,1))
    
    def addVartex(self,weights):
        if len(weights) != self.v:
            return
        self.weights.extend(weights)

    def addAdjMat(self, mat):
        for i,mat_i in enumerate(mat):
            for j,w in enumerate(mat_i):
                self.edge.append((i,j,w))

    def buildTree(self):
        pass

    def buildGraph(self):
        return Graph(self.v,self.edge,directed=self.directed)

def main():
    n,m = tuple([int(t)for t in input().split()])
    edge = []
 
    for i in range(m):
        a,b = tuple([int(t)for t in input().split()])
        edge.append((a-1,b-1,1))
    
    gb = GraphBuilder(n,edge=edge)
    g = gb.buildGraph()
    
    ans = g.dijkstra(0)[1]
    for a_i in ans[1:]:
      print(a_i+1)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def Func(rooms, n):
	distances = []
	for start in range(2, n+1):
		hasFound = False
		roomsToFind = [[start],]
		dist = 0
		while not hasFound:
			dist += 1
			for room in rooms[roomsToFind[0][-1]-1].connected:
				if room.ID == 1:
					if dist == 1:
						distances.append(1)
					else:
						distances.append(roomsToFind[0][1])
					hasFound = True
					break
				a = roomsToFind[0].copy()
				a.append(room.ID)
				roomsToFind.append(a)
			roomsToFind.pop(0)
			if dist > n and hasFound == False:
				print("No")
				return
	print("Yes")
	for num in distances:
		print(num)

class Room:
	def __init__(self, ID):
		self.ID = ID
		self.connected = []

	def add(self, room):
		self.connected.append(room)


n, m = list(map(int, input().split()))
rooms = [Room(i) for i in range(1, n+1)]

for i in range(m):
	beg, end = list(map(int, input().split()))

	rooms[beg-1].add(rooms[end-1])
	rooms[end-1].add(rooms[beg-1])

Func(rooms, n)

Submission status: Wrong Answer

Solution code:
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

def dfs(graph,s,n):
    stack=[]
    visited=[False for _ in xrange(n+1)]
    ans = [None for _ in xrange(n+1)]
    stack=[s]
    while stack:
        node=stack.pop()
        if not visited[node]:
            for nodes in graph[node]:
                if ans[nodes] is None:
                    ans[nodes] = str(node)
                stack.append(nodes)
            visited[node] = True
    return ans


n,m = (int(x) for x in input().split())
graph = dict()
for x in xrange(m):
    a,b = (int(x) for x in input().split())
    try:
        graph[a].append(b)
    except:
        graph[a] = [b]
    try:
        graph[b].append(a)
    except:
        graph[b] = [a]
print("No")
"""
ans = [None for _ in xrange(n+1)]
ans = dfs(graph,1,n)
if None in ans[1:]:
    print('No')
else:
    print('Yes')
    print('\n'.join(ans[2:]))
"""

Submission status: Wrong Answer

Solution code:
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

def dfs(graph,s,n):
    stack=[]
    visited=[False for _ in xrange(n+1)]
    ans = [None for _ in xrange(n+1)]
    stack=[s]
    while stack:
        node=stack.pop()
        if not visited[node]:
            for nodes in graph[node]:
                if ans[nodes] is None:
                    ans[nodes] = str(node)
                stack.append(nodes)
            visited[node] = True
    return ans


n,m = (int(x) for x in input().split())
graph = dict()
for x in xrange(m):
    a,b = (int(x) for x in input().split())
    try:
        graph[a].append(b)
    except:
        graph[a] = [b]
    try:
        graph[b].append(a)
    except:
        graph[b] = [a]
ans = [None for _ in xrange(n+1)]
ans = dfs(graph,1,n)
if None in ans[1:]:
    print('No')
else:
    print('Yes')
    print('\n'.join(ans[2:]))

Submission status: Wrong Answer

Solution code:
import math
import queue
from collections import defaultdict
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 i in toarr:
		if flg[i]==-1:
			flg[i]=fr
def addQueue(arr):
	global q
	for i in arr:
		q.put(i)
def addFQ(item):
	global flg
	global q
	global ab
	for i in ab[item]:
		if flg[i]==-1:
			flg[i]=item
		q.put(i)


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

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

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

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

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

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
root = [set() for i in range(N + 1)]
ans = [0 for i in range(N + 1)]
for i in range(M):
    a, b = map(int, input().split())
    root[a].add(b)
    root[b].add(a)
task = [1]
itta = {1}
while len(task) > 0:
    now = task[0]
    print(now)
    additional = root[now] - itta
    for i in additional:
        ans[i] = now
        itta.add(i)
    task = task[1:] + list(additional)
print("Yes")
for i in range(2, N + 1):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

def dfs(graph,s,n):
    stack=[]
    visited=[False for _ in xrange(n+1)]
    ans = [None for _ in xrange(n+1)]
    stack=[s]
    while stack:
        node=stack.pop()
        if not visited[node]:
            for nodes in graph[node]:
                if ans[nodes] is None:
                    ans[nodes] = str(node)
            visited[node] = True
            stack=stack+list(graph[node])
    return ans


n,m = (int(x) for x in input().split())
graph = dict()
for x in xrange(m):
    a,b = (int(x) for x in input().split())
    try:
        graph[a].append(b)
    except:
        graph[a] = [b]
    try:
        graph[b].append(a)
    except:
        graph[b] = [a]
ans = [None for _ in xrange(n+1)]
ans = dfs(graph,1,n)
if None in ans[1:]:
    print('No')
else:
    print('Yes')
    print('\n'.join(ans[2:]))

Submission status: Wrong Answer

Solution code:
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

def dfs(graph,s,ans):
    stack=[]
    visited=[]
    stack=[s]
    while stack:
        node=stack.pop()
        if node not in visited:
            for nodes in graph[node]:
                if ans[nodes] is None:
                    ans[nodes] = node
            visited.append(node)
            stack=stack+list(graph[node])
    return ans


n,m = (int(x) for x in input().split())
graph = dict()
for x in xrange(m):
    a,b = (int(x) for x in input().split())
    try:
        graph[a].append(b)
    except:
        graph[a] = [b]
    try:
        graph[b].append(a)
    except:
        graph[b] = [a]
ans = [None for _ in xrange(n+1)]
ans = dfs(graph,1,ans)
if None in ans[1:]:
    print('No')
else:
    print('Yes')
    for i in xrange(n-1):
        print(ans[2+i])

Submission status: Wrong Answer

Solution code:
import queue

def readInts():
	return list(map(int, input().split()))

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]==-1:
			flg[to-1]=fr
def addQueue(arr):
	global q
	for i in arr:
		q.put(i)

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

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

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

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

print("Yes")
for i in flg:
	print(i+1)