jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
#!/usr/bin/env python3

import sys
sys.setrecursionlimit(300000)

YES = "Yes"  # type: str

def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    conns = [[] for _ in range(N)]
    for i in range(M):
        conns[A[i] - 1].append(B[i] - 1)
        conns[B[i] - 1].append(A[i] - 1)

    q = [0]
    ret = [-1] * N
    visited = [False] * N
    visited[0] = True
    while True:
        nex = []
        for i in q:
            for con in conns[i]:
                if not visited[con]:
                    nex.append(con)
                    ret[con] = i
                    visited[con] = True
        if len(nex) == 0:
            break
        q = nex
    for r in ret[1:]:
        if r < 0:
            print('No')
            return
    print('Yes')
    for r in ret[1:]:
        print(r + 1)
    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()
//  [python]
from collections import deque
N, M = map(int, input().split())
route = [[] for _ in range(N)]
for _ in range(M):
  A, B = map(int, input().split())
  route[A-1].append(B-1)
  route[B-1].append(A-1)

tmp = 0
prv = 0
visited = [False]*N
kouho = deque()
ans = [-1]*(N)

for room in route[0]:
  kouho.append([room,0])
while kouho:
  visited[tmp] = True
  ans[tmp] = prv
  for room in route[tmp]:
    if not visited[room]:
      kouho.append([room,tmp])
  while kouho:
    tmp_ = kouho.popleft()
    tmp = tmp_[0]
    prv = tmp_[1]
    if not visited[tmp]:
      break
if -1 not in ans:
  print("Yes")
  for n in range(1,N):
    print(ans[n]+1)
else:
  print("No")
//  [python]
from collections import deque
N, M = map(int, input().split())
route = [[] for _ in range(N)]
for _ in range(M):
  A, B = map(int, input().split())
  route[A-1].append(B-1)
  route[B-1].append(A-1)

tmp = 0
prv = 0
visited = [False]*N
kouho = deque()
ans = [-1]*(N)

for room in route[0]:
  kouho.append([room,0])
while kouho:
  visited[tmp] = True
  ans[tmp] = prv
  for room in route[tmp]:
    if not visited[room]:
      kouho.append([room,tmp])
  while kouho:
    tmp_ = kouho.popleft()
    tmp = tmp_[0]
    prv = tmp_[1]
    if not visited[tmp]:
      break
print("Yes")
for n in range(1,N):
  print(ans[n]+1)
//  [python]
from collections import deque
N, M = map(int, input().split())
route = [[] for _ in range(N)]
for _ in range(M):
  A, B = map(int, input().split())
  route[A-1].append(B-1)
  route[B-1].append(A-1)

tmp = 0
prv = 0
visited = [False]*N
kouho = deque()
ans = [-1]*(N)

for room in route[0]:
  kouho.append([room,0])
while kouho:
  visited[tmp] = True
  ans[tmp] = prv
  for room in route[tmp]:
    if not visited[room]:
      kouho.append([room,tmp])
  while kouho:
    tmp_ = kouho.popleft()
    tmp = tmp_[0]
    prv = tmp_[1]
    if not visited[tmp]:
      break
print("Yes")
for n in range(1,N):
  print(ans[n])
//  [java]
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int N = scan.nextInt();
		int M = scan.nextInt();
		int a,b;
		boolean[][] road = new boolean[N+1][N+1];
		for(int i = 0; i < M; i++) {
			a = scan.nextInt();
			b = scan.nextInt();
			if (a < b) {
				road[a][b] = true;
			} else {
				road[b][a] = true;
			}
		}

		Queue<Integer> order = new ArrayDeque<>();
		boolean[] visit = new boolean[N+1];
		order.add(1);
		visit[0] = true;
		visit[1] = true;
		int[] number = new int[N+1];
		int n;

		while (!order.isEmpty()) {
			n = order.poll();
			for (int i = 1; i < N+1; i++) {
				if (n < i) {
					if (road[n][i] && !visit[i]) {
						order.add(i);
						visit[i] = true;
						number[i] = n;
					}
				} else if (i < n){
					if (road[i][n] && !visit[i]) {
						order.add(i);
						visit[i] = true;
						number[i] = n;
					}
				}
			}
		}

		System.out.println("Yes");
		for (int i = 2; i < N+1; i++) {
			System.out.println(number[i]);
		}
	}
}
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += 72 - dig >> 3;
	return tmp;
}
const int dm = 1 << 20;
char dn[dm], * di = dn;
inline void putint(int X) {
	int keta = 0;
	char C[10];
	while (X) {
		*(C + keta) = '0' + X % 10;
		X /= 10;
		keta++;
	}
	for (int i = keta - 1; i >= 0; i--)* di++ = (*(C + i));
	*di++ = '\n';
}

int to[400004], ne[400004], he[100001];
int kotae[100001], Q[100001];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint(), M = getint();
	int k = 1;
	rep(i, M) {
		int a = getint(), b = getint();
		to[k] = b;
		ne[k] = he[a];
		he[a] = k++;
		to[k] = a;
		ne[k] = he[b];
		he[b] = k++;
	}

	int q = 0;
	Q[q++] = 1;
	kotae[1] = 1;
	rep(i, N) {
		int u = Q[i];
		for (int v = he[u]; v; v = ne[v]) {
			int To = to[v];
			if (!kotae[To]) {
				kotae[To] = u;
				Q[q++] = To;
			}
		}
	}
	printf("Yes\n");

	for (int i = 2; i <= N; i++) putint(kotae[i]);
	fwrite(dn, 1, di - dn, stdout);

	Would you please return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;

const inf INF = 1001001001;
vector<int> to[100005]

int main() {
    //スタートからの距離-1のノードへの指示ができればok
    //幅優先探索をすれば良い
    //各ノードにスタートからの距離とどこから来たか(たどるため)を記録する

    int n, m;
    cin >> n >> m;
    rep(i, m){
        int a, b;
        cin >> a >> b;
        --a; --b;
        //push_backは末尾に追加
        to[a].push_back(b);
        to[b].push_back(a);
    }

    queue<int> q;
    vector<int> dist(n, INF);
    vector<int> pre(n, -1);
    dist[0] = 0;
    q.push(0);
    while(!q.empty()){
        //queueの先頭を取り出し
        int v = q.front(); q.pop();
        //vとつながっているノードをなめていく
        for (int u: to[v]){
            if(dist[u] != INF) continue;
            dist[u] = dist[v] + 1;
            //親を記録
            pre[u] = v;
            //訪問済みにする
            q.push(u);
        }
    }

    //今回はどの部屋もつながっている条件があるので必ずYes
    cout << "Yes" << endl;
    rep(i, n){
        if(i == 0) continue;
        int ans = pre[i];
        ++ans;
        cout << ans << endl;
    }

    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
vector<int> visited;
vector<vector<int> > adj;
vector<int> parent;
vector<int> dp;
void dfs(int s,int p)
{
    visited[s]=1;
    for(auto it:adj[s])
    {
         if(dp[it]>dp[s]+1)
        {
            dp[it]=dp[s]+1;
            parent[it]=s;
        }
        if(!visited[it])
        dfs(it,s);
       
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    adj.resize(n+1);
    visited.resize(n+1);
    parent.resize(n+1);
    dp.resize(n+1,1e7);
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin>>x>>y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    dp[1]=0;
    dfs(1,-1);
    
    for(int i=2;i<=n;i++)
    {
        if(!visited[i])
        {
            cout<<"No"<<endl;
            return 0;
        }
    }
    cout<<"Yes"<<endl;
    for(int i=2;i<=n;i++) 
    cout<<parent[i]<<endl;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
vector<int> visited;
vector<vector<int> > adj;
vector<int> parent;
void dfs(int s,int p)
{
    visited[s]=1;
    parent[s]=p;
    for(auto it:adj[s])
    {
        if(!visited[it])
        dfs(it,s);
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    adj.resize(n+1);
    visited.resize(n+1);
    parent.resize(n+1);
    for(int i=0;i<m;i++)
    {
        int x,y;
        cin>>x>>y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    dfs(1,-1);
    for(int i=2;i<=n;i++)
    {
        if(!visited[i])
        {
            cout<<"No"<<endl;
            return 0;
        }
    }
    cout<<"Yes"<<endl;
    for(int i=2;i<=n;i++) 
    cout<<parent[i]<<endl;
}
//  [c]
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif

char rbuf[2800014];
char wbuf[699997];
int rbufl, wbufl;

#define getchar_unlocked() rbuf[rbufl++]
#define putchar_unlocked(c) wbuf[wbufl++]=(c)

inline uint32_t nextpint(void){ char c=getchar_unlocked(); uint32_t x=0; while('0'<=c){ x=x*10+c-'0'; c=getchar_unlocked(); } return x; }
inline void printpint(int32_t x){ if(x==0){putchar_unlocked('0');} int d=0; char s[10]; while(x){ s[d]='0'+x%10; x/=10; d++; } for (int i=d-1; i>=0; i--) putchar_unlocked(s[i]); putchar_unlocked('\n'); }

int edge[200000][2];

int qmem[400000];

int *e[100001];
int el[100001];

int prev[100001];

int s[100000];
int sl, sr;

int main(void){
	read(STDIN_FILENO, rbuf, sizeof(rbuf));
	int n=nextpint();
	int m=nextpint();
	for(int i=0; i<m; i++){
		int A=nextpint();
		int B=nextpint();
		edge[i][0]=A;
		edge[i][1]=B;
		el[A]++;
		el[B]++;
	}
	int ne=0;
	for(int i=1; i<=n; i++){
		e[i]=&qmem[ne];
		ne+=el[i];
		el[i]=0;
	}
	for(int i=0; i<m; i++){
		int A=edge[i][0];
		int B=edge[i][1];
		e[A][el[A]++]=B;
		e[B][el[B]++]=A;
	}
	int k=0;
	prev[1]=1;
	s[sr++]=1;
	while(sl<sr){
		k++;
		int from = s[sl++];
		for(int i=0; i<el[from]; i++){
			int to = e[from][i];
			if(prev[to]==0){
				prev[to]=from;
				s[sr++]=to;
			}
		}
	}
	if(k==n){
		putchar_unlocked('Y');
		putchar_unlocked('e');
		putchar_unlocked('s');
		putchar_unlocked('\n');
		for(int i=2; i<=n; i++){
			printpint(prev[i]);
		}
		write(STDOUT_FILENO, wbuf, wbufl);
	}else{
		puts("No");
	}
}
//  [c]
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif

char rbuf[2800014];
char wbuf[699997];
int rbufl, wbufl;

#define getchar_unlocked() rbuf[rbufl++]
#define putchar_unlocked(c) wbuf[wbufl++]=(c)

uint32_t nextpint(void){ char c=getchar_unlocked(); uint32_t x=0; while('0'<=c){ x=x*10+c-'0'; c=getchar_unlocked(); } return x; }
void printpint(int32_t x){ if(x==0){putchar_unlocked('0');} int d=0; char s[10]; while(x){ s[d]='0'+x%10; x/=10; d++; } for (int i=d-1; i>=0; i--) putchar_unlocked(s[i]); putchar_unlocked('\n'); }

int edge[200000][2];

int qmem[400000];

int *e[100001];
int el[100001];

int prev[100001];

int s[100000];
int sl, sr;

int main(void){
	read(STDIN_FILENO, rbuf, sizeof(rbuf));
	int n=nextpint();
	int m=nextpint();
	for(int i=0; i<m; i++){
		int A=nextpint();
		int B=nextpint();
		edge[i][0]=A;
		edge[i][1]=B;
		el[A]++;
		el[B]++;
	}
	int ne=0;
	for(int i=1; i<=n; i++){
		e[i]=&qmem[ne];
		ne+=el[i];
		el[i]=0;
	}
	for(int i=0; i<m; i++){
		int A=edge[i][0];
		int B=edge[i][1];
		e[A][el[A]++]=B;
		e[B][el[B]++]=A;
	}
	int k=0;
	prev[1]=1;
	s[sr++]=1;
	while(sl<sr){
		k++;
		int from = s[sl++];
		for(int i=0; i<el[from]; i++){
			int to = e[from][i];
			if(prev[to]==0){
				prev[to]=from;
				s[sr++]=to;
			}
		}
	}
	if(k==n){
		putchar_unlocked('Y');
		putchar_unlocked('e');
		putchar_unlocked('s');
		putchar_unlocked('\n');
		for(int i=2; i<=n; i++){
			printpint(prev[i]);
		}
		write(STDOUT_FILENO, wbuf, wbufl);
	}else{
		puts("No");
	}
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

#define ll long long
#define ARR_SIZE 210000
#define MOD ((ll)1e9 + 7)

typedef struct __node__ {
    int data;
    struct __node__ *next;
} Node;

int main(){
    int n, m, a[ARR_SIZE] = {}, b[ARR_SIZE] = {};
    scanf("%d %d", &n, &m);
    for(int i=0;i<m;i++) scanf("%d %d", a+i, b+i);
    // end input

    Node* room[ARR_SIZE];
    for(int i=1;i<=n;i++) room[i] = NULL;

    for(int path=0;path<m;path++){
        Node* p0 = calloc(1, sizeof(Node));
        p0->data = a[path];
        p0->next = room[b[path]];
        room[b[path]] = p0;

        Node* p1 = calloc(1, sizeof(Node));
        p1->data = b[path];
        p1->next = room[a[path]];
        room[a[path]] = p1;
    }

    int next_room[ARR_SIZE] = {};
    int child_room[ARR_SIZE] = {1};
    int child_room0[ARR_SIZE] = {};
    int num_children = 1;
    int num_children0 = 0;
    int flag = 1;

    if(room[1]==NULL){
        printf("No\n");
        return 0;
    }
    
    while(flag == 1){
        flag = 0;
        for(int i=0;i<num_children;i++){
            int parent_room = child_room[i];

            Node* ptr = room[parent_room];
            while(ptr!=NULL){
                int data = ptr->data;
                if(next_room[data]>0){
                    ptr = ptr->next;
                    continue;
                }
                next_room[data] = parent_room;
                child_room0[num_children] = data;
                num_children0 += 1;
                ptr = ptr->next;
                flag = 1;
            }
        }

        num_children = num_children0;
        for(int j=0;j<num_children;j++){
            child_room[j] = child_room0[j];
        }
        num_children0 = 0;
    }

    int count = 0;
    for(int r=2;r<=n;r++){
        if(next_room[r]>0){
            count += 1;
        }
    }

    if(count==n-1){
        printf("Yes\n");
        for(int r=2;r<=n;r++){
            printf("%d\n", next_room[r]);
        }
    }
    


    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

#define ll long long
#define ARR_SIZE 210000
#define MOD ((ll)1e9 + 7)

typedef struct __node__ {
    int data;
    struct __node__ *next;
} Node;

int main(){
    int n, m, a[ARR_SIZE] = {}, b[ARR_SIZE] = {};
    scanf("%d %d", &n, &m);
    for(int i=0;i<m;i++) scanf("%d %d", a+i, b+i);
    // end input

    Node* room[ARR_SIZE];
    for(int i=1;i<=n;i++) room[i] = NULL;

    for(int path=0;path<m;path++){
        Node* p0 = calloc(1, sizeof(Node));
        p0->data = a[path];
        p0->next = room[b[path]];
        room[b[path]] = p0;

        Node* p1 = calloc(1, sizeof(Node));
        p1->data = b[path];
        p1->next = room[a[path]];
        room[a[path]] = p1;
    }

    int next_room[ARR_SIZE] = {};
    int child_room[ARR_SIZE] = {1};
    int child_room0[ARR_SIZE];
    int num_children = 1;
    int num_children0 = 0;
    int flag = 1;

    if(room[1]==NULL){
        printf("No\n");
        return 0;
    }
    
    while(flag == 1){
        flag = 0;
        for(int i=0;i<num_children;i++){
            int parent_room = child_room[i];

            Node* ptr = room[parent_room];
            while(ptr!=NULL){
                int data = ptr->data;
                if(next_room[data]>0){
                    ptr = ptr->next;
                    continue;
                }
                next_room[data] = parent_room;
                child_room0[num_children] = data;
                num_children0 += 1;
                ptr = ptr->next;
                flag = 1;
            }
        }

        num_children = num_children0;
        for(int j=0;j<num_children;j++){
            child_room[j] = child_room0[j];
        }
        num_children0 = 0;
    }

    int count = 0;
    for(int r=2;r<=n;r++){
        if(next_room[r]>0){
            count += 1;
        }
    }

    if(count==n-1){
        printf("Yes\n");
        for(int r=2;r<=n;r++){
            printf("%d\n", next_room[r]);
        }
    }
    


    return 0;

    printf("---------------------------------\n");
    for(int r=1;r<=n;r++){
        Node *ptr = room[r];
        while(ptr!=NULL){
            printf("%d ", ptr->data);
            ptr = ptr->next;
        }
        printf("\n");
    }

    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

#define ll long long
#define ARR_SIZE 210000
#define MOD ((ll)1e9 + 7)


int main(){
    int n, m, a[ARR_SIZE] = {}, b[ARR_SIZE] = {};
    scanf("%d %d", &n, &m);
    for(int i=0;i<m;i++) scanf("%d %d", a+i, b+i);
    // end input

    int depth[ARR_SIZE] = {}, next[ARR_SIZE] = {};

    depth[1] = 1;
    next[1] = 1;
    for(int d=1;d<=n;d++){
        for(int r=1;r<=n;r++){
            if(depth[r]==d){
                //printf("room: %d, depth: %d\n", r, d);
                for(int i=0;i<m;i++){
                    if(b[i]==r){
                        //printf("00room: %d, path: %d %d\n", r, a[i], b[i]);
                        b[i] = a[i];
                        a[i] = r;
                    }
                    
                    if(a[i]==r){
                        //printf("room: %d, path: %d %d\n", r, a[i], b[i]);
                        if(depth[b[i]]>0) continue;
                        depth[b[i]] = depth[r] + 1;
                        next[b[i]] = r;
                        
                        a[i] = a[m-1];
                        b[i] = b[m-1];
                        m -= 1;
                    }
                }
            }
        }
        int count = 0;
        for(int r=1;r<=n;r++){
            if(next[r]>0){
                count++;
            }
        }
        if(count==n) break;
    }
    
    int count = 0;
    for(int r=1;r<=n;r++){
        if(next[r]>0){
            count++;
        }
    }

    if(count==n){
        printf("Yes\n");
        for(int r=2;r<=n;r++){
            printf("%d\n", next[r]);
        }
    }else{
        printf("No\n");
    }

    return 0;
}
//  [javascript]
function main(lines) {
  const [N, M] = splitN(lines[0]);

  const map = Array(N+1).fill(0).map(() => []);
  for (let i = 1; i <= M; i++) {
    const [a, b] = splitN(lines[i]);
    map[a].push(b);
    map[b].push(a);
  }
  const res = [null];
  for (let current = [1]; true; ) {
    const next = [];
    current.forEach(c => {
      map[c].forEach(n => {
        if (res[n-1] !== undefined) return;
        res[n-1] = c;
        next.push(n);
      });
    });
    if (!next.length) break;
    current = next;
  }
  
  if (res.filter(i => i !== undefined).length === N) {
    res[0] = 'Yes';
    console.log( res.join('\n') );
  } else {
    console.log('No');
  }
}


main( require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n") );



function splitN(s) {
  return s.split(' ').map(Number);
}
//  [javascript]
function main(lines) {
  const [N, M] = splitN(lines[0]);

  const map = Array(N+1).fill(0).map(() => []);
  for (let i = 1; i <= M; i++) {
    const [a, b] = splitN(lines[i]);
    map[a].push(b);
    map[b].push(a);
  }
  const res = [null];
  for (let current = [1]; true; ) {
    const next = [];
    current.forEach(c => {
      map[c].forEach(n => {
        if (res[n-1] !== undefined) return;
        res[n-1] = c;
        next.push(n);
      });
    });
    if (!next.length) break;
    current = next;
  }
  
  res[0] = 'Yes';
  console.log( res.join('\n') );
}


main( require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n") );



function splitN(s) {
  return s.split(' ').map(Number);
}
//  [javascript]
const main = (input) => {
  const [a, ...qs] = input.trim().split('\n')
  const [N,] = a.split(' ').map(Number)
  const q = qs.map(v => v.split(' '))

  const cave = new Array(N+1).fill().map(() => [])

  for (let [a, b] of q) {
    cave[a].push(b)
    cave[b].push(a)
  }

  const visited = { '1': true }
  const ans = ['Yes', ...new Array(N).fill(0)]
  let queue = [1]

  while (queue.length) {
    const nextQ = []
    while (queue.length) {
      const v = queue.shift()
      const links = cave[v]

      for (let l of links) {
        if (visited[l]) continue
        nextQ.push(l)
        ans[l] = v
        visited[l] = true
      }
    }

    queue = nextQ
  }

  for (let i=0; i<=N; i++) {
    if (i===1) continue
    console.log(ans[i])
  }
  return null
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
const main = (input) => {
  const [a, ...qs] = input.trim().split('\n')
  const [N, M] = a.split(' ').map(Number)
  const q = qs.map(v => v.split(' '))

  const cave = new Array(N+1).fill([])

  for (let [a, b] of q) {
    cave[a] = [...cave[a], b]
    cave[b] = [...cave[b], a]
  }

  const visited = { '1': true }
  const ans = ['Yes', ...new Array(N).fill(0)]
  let queue = [1]

  while (queue.length) {
    const nextQ = []
    while (queue.length) {
      const v = queue.shift()
      const links = cave[v]

      for (let l of links) {
        if (visited[l]) continue
        nextQ.push(l)
        ans[l] = v
        visited[l] = true
      }
    }

    queue = nextQ
  }

  for (let i=0; i<=N; i++) {
    if (i===1) continue
    console.log(ans[i])
  }
  return null
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]

let input = require("fs").readFileSync("/dev/stdin", "utf8")

function main({ input, load, yesno, math_sum, log_json }) {
    const [N,M] = load(2)
    const [A,B] = load(M,2)
    
    const rooms = new Array(N+1).fill(0)    // [room] = sign
    rooms[0] = -1
    rooms[1] = -1

    const rest = [1]
    while(rest.length) {
        inifinite_loop_preventer()

        const room = rest.shift()
        for(let i = 0; i < M; i++) {
            let from = null, to = null

            if(A[i] === room) [from, to] = [B[i], A[i]]
            if(B[i] === room) [from, to] = [A[i], B[i]]
            if(from === null) continue

            if(!rooms[from]) {
                rooms[from] = to
                rest.push(from)
            }
        }
    }

    if(rooms.includes(0)) return 'No'
    
    console.log('Yes')
    return rooms.slice(2).join('\n')
}



// console.time()
let inputs = input.split(/[\s\n]/)
let inifinite_loop_prevent_counter = 0
let result = main({
    input,
    yesno: value => value ? 'Yes' : 'No',
    math_sum: numbers => numbers.reduce((acc, cur) => acc + cur, 0),
    load(rows = 1, cols = 1, type = Number) {
        const length = rows * cols
        let result = inputs.splice(0, length)
        if(type !== String) result = result.map(type)
        if(cols > 1) {
            const arrays = new Array(cols)
            for(let col = 0; col < cols; col++) {
                arrays[col] = new Array()
                for(let row = 0; row < rows; row++) {
                    arrays[col].push(result[row * cols + col])
                }
            }
            result = arrays
        }
        return result
    },
    log_json(value) {
        console.log(JSON.stringify(value))
    },
})

if(result === undefined) {
    console.warn("result is undefined")
} else {
    console.log(result)
}
// console.timeEnd()


function inifinite_loop_preventer(max = 1e5) {
    inifinite_loop_prevent_counter++
    if(inifinite_loop_prevent_counter >= max) {
        throw new Error("Infinite loop")
    }
}

function math_max(numbers, initial_value = null) {
    let result = (initial_value === null) ? numbers[0] : initial_value
    for(const n of numbers) if(n > result) result = n
    return result
}

function math_min(numbers, initial_value = null) {
    let result = (initial_value === null) ? numbers[0] : initial_value
    for(const n of numbers) if(n < result) result = n
    return result
}

// 素因数分解 { 素数: n乗 }
function math_prime_factors(n) {
    const result = {}

    for(let i = 2; i * i <= n; i++) {
        if(n % i === 0) {
            n /= i
            result[i] = 1
            
            while(n % i === 0) {
                n /= i
                result[i]++
            }
        }
    }

    if(n > 1) result[n] = 1

    return result
}
//  [go]
package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	type pair struct{ v, fa int }

	n, m := r(), r()
	g := make([][]int, n+1)
	for ; m > 0; m-- {
		v, w := r(), r()
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := make([]int, n+1)
	vis := make([]bool, n+1)
	q := []pair{{1, 0}}
	vis[1] = true
	cnt := 1
	for len(q) > 0 {
		p := q[0]
		q = q[1:]
		v := p.v
		for _, w := range g[v] {
			if w != p.fa && !vis[w] {
				vis[w] = true
				cnt++
				ans[w] = v
				q = append(q, pair{w, v})
			}
		}
	}
	if cnt < n {
		Fprint(out, "No")
		return
	}
	Fprintln(out, "Yes")
	for _, v := range ans[2:] {
		Fprintln(out, v)
	}
}

func main() { run(os.Stdin, os.Stdout) }
//  [go]
// 1からスタンプを押していくBFS
// golangでpriority queueもってないから愚直FIFOで間に合うかどうかは正直わからん
// ちょっとだけIOを高速化したバージョン
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

type Pos struct {
	cur, pre int
}

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func main() {
	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush()
	N, M := nextInt(), nextInt()

	T := make([][]int, N+1)
	for i := 1; i <= N; i++ {
		T[i] = []int{}
	}
	for i := 0; i < M; i++ {
		A, B := nextInt(), nextInt()
		T[A] = append(T[A], B)
		T[B] = append(T[B], A)
	}
	passed := make([]int, N+1)
	passed[1] = -1
	queue := []Pos{Pos{cur: 1, pre: 0}}
	for len(queue) > 0 {
		nex_queue := []Pos{}
		for i := 0; i < len(queue); i++ {
			now := queue[i]
			for _, nex := range T[now.cur] {
				if passed[nex] == 0 {
					nexPos := Pos{cur: nex, pre: now.cur}
					passed[nex] = now.cur
					nex_queue = append(nex_queue, nexPos)
				}
			}
		}
		queue = nex_queue
	}
	fmt.Fprintln(out, "Yes")
	for _, ans := range passed[2:] {
		fmt.Fprintln(out, ans)
	}

}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}
//  [go]
package main
import (
    "fmt"
)
func main(){
    var n, m int
    fmt.Scan(&n)
    fmt.Scan(&m)
    
    // cango := make(map[int][]int)
    cango := make([][]int, 100010)
    
    for i := 0; i < m; i++ {
        var a, b int
        fmt.Scan(&a)
        fmt.Scan(&b)
        
        cango[a] = append(cango[a], b)
        cango[b] = append(cango[b], a)
    }
    
    var q Queue
    q.Add(1)
    
    // togo := make(map[int]int)
    togo := make([]int, 100010)
    
    for len(q) > 0 {
        now := q.Remove()
        for i := 0; i < len(cango[now]); i++ {
            if togo[cango[now][i]] == 0 {
                togo[cango[now][i]] = now
                q.Add(cango[now][i])
            }
        }
    }
    
    var ans []int
    for i := 2; i <= n; i++ {
        if x := togo[i]; x != 0 {
            ans = append(ans, x)
        } else {
            fmt.Println("No")
            return
        }
    }
    
    fmt.Println("Yes")
    for i := 0; i < len(ans); i++ {
        fmt.Println(ans[i])
    }
}

type Queue []int

func (q *Queue) Add (n int) {
    *q = append(*q, n)
}

func (q *Queue) Remove () int {
    temp := *q
    *q = temp[1:]
    return temp[0]
}
//  [go]
package main
import (
    "fmt"
)
func main(){
    var n, m int
    fmt.Scan(&n)
    fmt.Scan(&m)
    
    cango := make(map[int][]int)
    for i := 0; i < m; i++ {
        var a, b int
        fmt.Scan(&a)
        fmt.Scan(&b)
        
        cango[a] = append(cango[a], b)
        cango[b] = append(cango[b], a)
    }
    
    var q Queue
    q.Add(1)
    
    togo := make(map[int]int)
    
    for len(q) > 0 {
        now := q.Remove()
        for i := 0; i < len(cango[now]); i++ {
            if _, ok := togo[cango[now][i]]; !ok  {
                togo[cango[now][i]] = now
                q.Add(cango[now][i])
            }
        }
    }
    
    fmt.Println("Yes")
    for i := 2; i <= n; i++ {
        if v, ok := togo[i]; ok {
            fmt.Println(v)
        }
    }
    
}

type Queue []int

func (q *Queue) Add (n int) {
    *q = append(*q, n)
}

func (q *Queue) Remove () int {
    temp := *q
    *q = temp[1:]
    return temp[0]
}
//  [go]
package main
import (
    "fmt"
)
func main(){
    var n, m int
    fmt.Scan(&n)
    fmt.Scan(&m)
    
    cango := make(map[int][]int)
    for i := 0; i < m; i++ {
        var a, b int
        fmt.Scan(&a)
        fmt.Scan(&b)
        
        cango[a] = append(cango[a], b)
        cango[b] = append(cango[b], a)
    }
    
    var q Queue
    q.Add(1)
    
    togo := make(map[int]int)
    
    for len(q) > 0 {
        now := q.Remove()
        for i := 0; i < len(cango[now]); i++ {
            if _, ok := togo[cango[now][i]]; !ok &&  {
                togo[cango[now][i]] = now
                q.Add(cango[now][i])
            }
        }
    }
    
    fmt.Println("Yes")
    for i := 2; i <= n; i++ {
        if v, ok := togo[i]; ok {
            fmt.Println(v)
        }
    }
}

type Queue []int

func (q *Queue) Add (n int) {
    *q = append(*q, n)
}

func (q *Queue) Remove () int {
    temp := *q
    *q = temp[1:]
    return temp[0]
}
//  [ruby]
n,m=gets.split.map(&:to_i)
to=Array.new(n+1){[]}
m.times do
  a,b=gets.split.map(&:to_i)
  to[a] << b
  to[b] << a
end
dist=0
d=[nil,0]
ans=[nil,1]
stock=[]
to[1].each do |j|
  stock << j
  ans[j]=1
end

while !stock.empty?
  s=stock.shift
  to[s].each do |t|
    unless ans[t]
      stock << t
      ans[t] = s
    end
  end
end

if ans[2..n+1].any? nil
  puts 'No'
else
  puts 'Yes'
  puts  ans[2..n+1]
end
//  [ruby]
n, m = gets.split.map(&:to_i)
graph = Array.new(n + 1) { [] }

m.times do
  a, b = gets.split.map(&:to_i)
  graph[a] << b
  graph[b] << a
end

dist = []
dist[1] = 0
queue = [1]
ret = []

while queue.any?
  v = queue.shift

  graph[v].each do |i|
    next if dist[i]

    dist[i] = dist[v] + 1
    queue << i
    ret[i] = v
  end
end

puts :Yes
puts ret.compact
//  [ruby]
END { load __FILE__ unless $stdin.eof? }

n, m = gets.split.map!(&:to_i)

nbrs = Array.new(n + 1) { [] }
m.times do
  a, b = gets.split.map!(&:to_i)
  nbrs[a] << b
  nbrs[b] << a
end

q = [1]
dir = Array.new(n + 1)
dir[0] = dir[1] = 0
while (x = q.shift)
  nbrs[x].each do |y|
    next if dir[y]
    dir[y] = x
    q << y
  end
end

if dir.all?
  puts :Yes, dir.drop(2)
else
  puts :No
end
//  [ruby]
n,m=gets.split.map(&:to_i)
to=Array.new(n+1){[]}
m.times do
  a,b=gets.split.map(&:to_i)
  to[a] << b
  to[b] << a
end
dist=0
d=[nil,0]
ans=[nil,1]
stock=[]
to[1].each do |j|
  stock << j
  ans[j]=1
end

while !stock.empty?
  s=stock.shift
  to[s].each do |t|
    unless ans[t]
      stock << t
      ans[t] = s
    end
  end
end
puts  ans[2..n+1]
//  [ruby]
n,m = gets.chomp.split(' ').map(&:to_i)
visited = Array.new(n,false)
ans = Array.new(n){0}
path = Array.new(n){Array.new(n){0}}
m.times do
    x,y = gets.chomp.split(' ').map(&:to_i)
    path[x-1][y-1] = 1
    path[y-1][x-1] = 1
end

s = [[0,0]]
while s.size > 0
    now = s.shift
    if visited[now[0]]
        next
    end
    visited[now[0]] = true
    ans[now[0]] = now[1]
    path[now[0]].size.times do |i|
        if path[now[0]][i] == 1
            s << [i,now[0]]
        end
    end
end

puts "Yes"
ans[1..-1].each do |a|
    puts a+1
end
//  [ruby]
def get_int_array
    gets.strip.split(' ').map(&:to_i)
end

n, m = get_int_array

ps = n.times.map{|i| Array.new(0) }

m.times.each{|i|
    p, q = get_int_array
    ps[p-1].push q-1
    ps[q-1].push p-1
}

ptos = n.times.map{|i| nil }

queue = []

ps[0].each{|i| queue.push [i, 0] }

while queue.any?
    pnext, pfrom = queue.shift
    if ptos[pnext].nil?
        ptos[pnext] = pfrom + 1 if ptos[pnext].nil?
        (ps[pnext] & pf).each{|i| queue.push [i, pnext] }
    end
end

ptos = ptos.drop(1)
# p pf
if ptos.any?{|i| i.nil? }
    puts 'No'
else
    puts 'Yes'
    puts ptos
end
//  [rust]
use proconio::*;

#[fastout]
fn run() {
    input! {
        n: usize,
        m: usize,
        mut e: [(usize, usize); m],
    }
    let mut cnt = vec![0; n];
    for e in e.iter_mut() {
        e.0 -= 1;
        e.1 -= 1;
        cnt[e.0] += 1;
        cnt[e.1] += 1;
    }
    let mut buf = vec![0usize; 2 * m];
    let mut buf = buf.as_mut_slice();
    let mut g = Vec::with_capacity(n);
    for c in cnt.iter() {
        let (x, y) = buf.split_at_mut(*c);
        g.push(x);
        buf = y;
    }
    for (a, b) in e {
        cnt[a] -= 1;
        g[a][cnt[a]] = b;
        cnt[b] -= 1;
        g[b][cnt[b]] = a;
    }
    let mut prev = vec![n; n];
    prev[0] = 0;
    let mut q = std::collections::VecDeque::new();
    q.push_back(0);
    while let Some(v) = q.pop_front() {
        for &u in g[v].iter() {
            if prev[u] == n {
                prev[u] = v;
                q.push_back(u);
            }
        }
    }
    println!("Yes");
    for p in prev.iter().skip(1) {
        println!("{}", *p + 1);
    }
}

fn main() {
    run();
}
//  [rust]
use proconio::*;

#[fastout]
fn run() {
    input! {
        n: usize,
        m: usize,
        mut e: [(usize, usize); m],
    }
    let mut cnt = vec![0; n];
    for e in e.iter_mut() {
        e.0 -= 1;
        e.1 -= 1;
        cnt[e.0] += 1;
        cnt[e.1] += 1;
    }
    let mut buf = vec![0usize; 2 * m];
    let mut buf = buf.as_mut_slice();
    let mut g = Vec::with_capacity(n);
    for c in cnt.iter() {
        let (x, y) = buf.split_at_mut(*c);
        g.push(x);
        buf = y;
    }
    for (a, b) in e {
        cnt[a] -= 1;
        g[a][cnt[a]] = b;
        cnt[b] -= 1;
        g[b][cnt[b]] = a;
    }
    let mut prev = vec![n; n];
    prev[0] = 0;
    let mut q = std::collections::VecDeque::with_capacity(n);
    q.push_back(0);
    while let Some(v) = q.pop_front() {
        for &u in g[v].iter() {
            if prev[u] == n {
                prev[u] = v;
                q.push_back(u);
            }
        }
    }
    println!("Yes");
    for p in prev.iter().skip(1) {
        println!("{}", *p + 1);
    }
}

fn main() {
    run();
}
//  [rust]
use proconio::*;

#[fastout]
fn run() {
    input! {
        n: usize,
        m: usize,
        mut e: [(usize, usize); m],
    }
    let mut cnt = vec![0; n];
    for e in e.iter_mut() {
        e.0 -= 1;
        e.1 -= 1;
        cnt[e.0] += 1;
        cnt[e.1] += 1;
    }
    let mut g: Vec<_> = cnt.into_iter().map(|c| Vec::with_capacity(c)).collect();
    for (a, b) in e {
        g[a].push(b);
        g[b].push(a);
    }
    let mut prev = vec![n; n];
    prev[0] = 0;
    let mut q = std::collections::VecDeque::new();
    q.push_back(0);
    while let Some(v) = q.pop_front() {
        for &u in g[v].iter() {
            if prev[u] == n {
                prev[u] = v;
                q.push_back(u);
            }
        }
    }
    println!("Yes");
    for p in prev.iter().skip(1) {
        println!("{}", *p + 1);
    }
}

fn main() {
    run();
}
//  [rust]
#![allow(non_snake_case)]
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let m: usize = read();
    let mut v: Vec<Vec<usize>> = vec![vec![]; n + 1];
    let mut shortest: Vec<i64> = vec![0; n + 1];
    let mut ansArr: Vec<usize> = vec![0; n + 1];
    shortest[1] = -1000;
    for _ in 0..m {
        let a: usize = read();
        let b: usize = read();
        &v[a].push(b);
        &v[b].push(a);
        if a == 1 {
            shortest[b] = 1;
            ansArr[b] = 1;
        } else if b == 1 {
            ansArr[a] = 1;
            shortest[a] = 1;
        }
        let mut aaaa = |index: usize| {
            if ansArr[index] != 0 {
                for i in &v[index] {
                    if shortest[*i] == 0 {
                        shortest[*i] = shortest[index] + 1;
                        ansArr[*i] = index;
                    } else {
                        if shortest[*i] > shortest[index] + 1{
                            shortest[*i] = shortest[index] + 1;
                            ansArr[*i] = index;
                        } else if shortest[*i] == shortest[index] + 1 {
                            // 特に意味ないけど同率なら小さい番号
                            if index > *i{
                                ansArr[*i] = index;
                            }
                        }
                    }
                }
                v[index].clear();
            }
        };
        aaaa(a);
        aaaa(b);
    }

    print!("Yes\n");
    for i in 2..n + 1 {
        print!("{}\n", ansArr[i]);
    }
}
//  [swift]
let first = readLine()!.split(separator: " ")
let N = Int(first[0])!
let M = Int(first[1])!

var graph: [[Int]] = .init(repeating: [], count: N)

for i in 0..<M {
  let line = readLine()!.split(separator: " ")
  let A = Int(line[0])!
  let B = Int(line[1])!
  graph[A-1].append(B-1)
  graph[B-1].append(A-1)
}

var anchor: [Int] = .init(repeating: -1, count: N)
var fixed = 0

var queue: [Int] = [0]

while !queue.isEmpty {
  var tmp: [Int] = []
  for top in queue {
  	for nei in graph[top] {
      if anchor[nei] == -1 {
        fixed += 1
        anchor[nei] = top
        tmp.append(nei)
      }
    }
  }
  queue = tmp
}

if fixed == N - 1 {
  print("No")
} else {
  print("Yes")
  for i in 1..<N {
    print(anchor[i] + 1)
  }
}
//  [swift]
import Foundation


func readInt() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}


func main() {
    let line = readInt()
    let N = line[0]
    let M = line[1]

    var graph = (0...N).map { _ in [Int]() }
    for _ in (1...M) {
        let ab = readInt()
        let a = ab[0]
        let b = ab[1]
        graph[a].append(b)
        graph[b].append(a)
    }

    var ans = [Int](repeating: -1, count: N + 1)
    var q = [1]
    while !q.isEmpty {
        var q_ = [Int]()
        for u in q {
            for v in graph[u] {
                guard ans[v] == -1 else { continue }
                ans[v] = u
                q_.append(v)
            }
        }
        q = q_
    }
    print("Yes")
    for i in ans[2...] {
        print(i)
    }
}

main()
//  [swift]
import Foundation


func readInt() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}


func main() {
    let line = readInt()
    let N = line[0]
    let M = line[1]

    var graph = (0...M).map { _ in [Int]() }
    for _ in (1...M) {
        let ab = readInt()
        let a = ab[0]
        let b = ab[1]
        graph[a].append(b)
        graph[b].append(a)
    }

    var ans = [Int](repeating: -1, count: N + 1)
    var q = ArraySlice<Int>()
    q.append(1)
    while let u = q.popFirst() {
        for v in graph[u] {
            guard ans[v] == -1 else { continue }
            ans[v] = u
            q.append(v)
        }
    }

    if ans[2...].contains(-1) {
        print("No")
        return
    }

    print("Yes")
    for i in ans[2...] {
        print(i)
    }

}

main()
//  [swift]
let (N, M) = readInts().mapToTuple()


struct Root: Equatable {
    let a, b: Int
    
    func other(of id: Int) -> Int? {
        if a == id { return b }
        if b == id { return a }
        return nil
    }
}

var roots: [Root] = (1...M).map { i in
    let (a, b) = readInts().mapToTuple()
    return Root(a: a, b: b)
}

var rooms = Array(repeating: Optional<Int>.none, count: N)

rooms[0] = 0
var old: Set<Int> = [1]
var now = [1]
while !now.isEmpty {
    for i in now {
        let rs = roots
            .compactMap { $0.other(of: i) }
            .filter { !old.contains($0) }
//        print(rs)
        old.formUnion(rs)
        now = rs
        for j in rs {
            rooms[j-1] = i
        }
    }
}

//print(rooms)
if rooms.allSatisfy({ $0 != nil }) {
    print("Yes")
    rooms[1...].forEach { print($0!) }
} else {
    print("No")
}



// MARK: -----------------------------------------------------------------------


func readInts() -> [Int] {
    readLine()!.split(separator: " ").map { Int($0)! }
}

extension Collection {
    func mapToTuple() -> (Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!, i.next()!)
    }
    
    subscript(gen: Index) -> Element {
        _modify { yield &self[index(gen, offsetBy: -1)] }
        _read   { yield self[index(gen, offsetBy: -1)] }
    }
}
//  [swift]
let (N, M) = readInts().mapToTuple()

struct Room: Equatable {
    let id: Int
    var roots = [Int]()
    var flags: Int?
}

struct Root: Equatable {
    let a, b: Int
    
    func other(of id: Int) -> Int? {
        if a == id { return b }
        if b == id { return a }
        return nil
    }
}

var roots: [Root] = (1...M).map { i in
    let (a, b) = readInts().mapToTuple()
    return Root(a: a, b: b)
}

var rooms: [Room] = (1...N).map { Room(id: $0) }

rooms[0].flags = 0
var old: Set<Int> = [1]
var now = [1]
while !now.isEmpty {
    for i in now {
        let rs = roots
            .compactMap { $0.other(of: i) }
            .filter { !old.contains($0) }
//        print(rs)
        old.formUnion(rs)
        now = rs
        for j in rs {
            rooms[j-1].flags = i
        }
    }
}

//print(rooms)
if rooms.allSatisfy({ $0.flags != nil }) {
    print("Yes")
    rooms[1...].forEach { print($0.flags!) }
} else {
    print("No")
}



// MARK: -----------------------------------------------------------------------


func readInts() -> [Int] {
    readLine()!.split(separator: " ").map { Int($0)! }
}

extension Collection {
    func mapToTuple() -> (Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!)
    }
    func mapToTuple() -> (Element, Element, Element, Element) {
        var i = makeIterator()
        return (i.next()!, i.next()!, i.next()!, i.next()!)
    }
}

struct DP<Argument: Hashable, Element> {
    var dictionary = [Argument: Element]()
    
    var expression: (Argument, (Argument) -> Element) -> Element
    
    init(expression: @escaping (_ argument: Argument, _ note: (Argument) -> Element) -> Element) {
        self.expression = expression
    }
    
    subscript(_ argument: Argument) -> Element {
        mutating get {
            if let note = dictionary[argument] {
                return note
            } else {
                let result = expression(argument) { self[$0] }
                dictionary[argument] = result
                return result
            }
        }
    }
}
//  [typescript]
import * as fs from 'fs';

const readString = (() => {
  const input = fs.readFileSync(0).toString();
  const words = input.split(/[ \n]/);
  let i = 0;
  return () => words[i++] || '';
})();
const readInt = () => parseInt(readString(), 10);

(function main() {
  const N = readInt();
  const M = readInt();
  const routes: { [n: number]: number[] } = {}
  const pairs = Array.from({ length: M }, () => {
    const A = readInt();
    const B = readInt();
    routes[A] = routes[A] || [];
    routes[A].push(B);
    routes[B] = routes[B] || [];
    routes[B].push(A);
  });
  const depth: { [n: number]: number } = { 1: 1 };
  const parent: { [n: number]: number } = {};
  const paths: number[] = [1];
  while (true) {
    const n = paths.pop();
    if (n == null) break;

    const rs = routes[n];
    for (const r of rs) {
      if (depth[r] == null) {
        depth[r] = depth[n] + 1;
        parent[r] = n;
        paths.unshift(r);
      }
    }
  }

  console.log('Yes');
  for (let i = 2; i <= N; i++) {
    console.log(parent[i]);
  }
})();
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const [N, M] = input[0].map(Number);

  const adjacencies = [...Array(N + 1)].map(() => Array<number>());
  for (let i = 1; i <= M; i++) {
    const [A, B] = input[i].map(Number);

    adjacencies[A].unshift(B);
    adjacencies[B].unshift(A);
  }

  const distances: number[] = [];
  const parents: number[] = [];

  distances[1] = 0;

  const queue = [1];
  while (true) {
    const current = queue.pop();
    if (current === undefined) {
      break;
    }

    adjacencies[current].forEach((adjacency) => {
      if (distances[adjacency] !== undefined) {
        return;
      }

      distances[adjacency] = distances[current] + 1;
      parents[adjacency] = current;

      queue.unshift(adjacency);
    });
  }

  return `Yes\n${parents.slice(2).join("\n")}`;
};

console.log(main(read()));
//  [typescript]
import { count } from 'console';

process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', (chunk) => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const [n, m] = inputs[0].split(' ').map(Number);
  let room: number[][] = Array.from(new Array(n), () => new Array());
  let rootList: number[][][] = new Array();
  let result: number[] = new Array();

  // 各部屋から移動できる部屋番号を格納
  for (let i = 1; i <= m; i++) {
    const [a, b] = inputs[i].split(' ').map(Number);

    room[a - 1].push(b);
    room[b - 1].push(a);
  }

  // 各部屋のルート探索
  for (let i = 1; i < n; i++) {
    const targetRoom = room[i];

    // 移動できる部屋が存在しない場合、エラー
    if (targetRoom.length === 0) {
      noExistRootMessage();
      return;
    }
    // ループするルート(-1のルート)を除いて、配列へ格納
    rootList.push(searchRoot(i + 1, [], room).filter((value) => value[0] !== -1));
  }

  // 部屋1に最小の移動回数で辿り着く次の部屋を格納
  for (const root of rootList) {
    if (root.length == 0) {
      noExistRootMessage();
      return;
    }

    let minCount = -1;
    let roomNumber = 0;

    for (const targetRoot of root) {
      if (minCount === -1 || minCount > targetRoot.length) {
        minCount = targetRoot.length;
        roomNumber = targetRoot[1];
      }
    }
    result.push(roomNumber);
  }

  console.log('Yes');
  result.forEach((value) => console.log(value));
}

function noExistRootMessage() {
  console.log('No');
}

// 各部屋のルートを全探索
// ループするルートは-1を返す
function searchRoot(roomNumber: number, root: number[], room: number[][]): number[][] {
  if (root.indexOf(roomNumber) !== -1) {
    return [[-1]];
  }

  if (roomNumber === 1) {
    root.push(1);
    return [root];
  }

  let rootList: number[][] = [];
  const nextRoom = room[roomNumber - 1];
  for (const nextRoomNumber of nextRoom) {
    rootList = rootList.concat(searchRoot(nextRoomNumber, root.concat(roomNumber), room));
  }
  return rootList;
}