1 #include<cstdio>
2 #include<cstdlib>
3 #include<iostream>
4 #include<queue>
5 #include<malloc.h>
6 #include<cstring>
7 #define N 100001
8
9 using namespace std;
10
11 typedef struct city
12 {
13 int v;
14 struct city *next;
15 }City;
16
17 City c[N];
18 int n,visit[N];
19 int father[N];
20
21 void connect(int from,int to)//连接两个点
22 {
23 City *p;
24 p = (City *)malloc(sizeof(City));
25 p->v = to;
26 p->next = c[from].next;
27 c[from].next = p;
28 }
29
30 void destory(City *p)//递归释放空间(从阿焦那里学的,嘻嘻~)
31 {
32 if(p == NULL)
33 return;
34 destory(p->next);
35 }
36
37 queue<City>q;
38 int main()
39 {
40 int i,j,ncases,S;
41 int a,b;
42 City *link;
43
44 scanf("%d",&ncases);
45 while( ncases-- )
46 {
47 scanf("%d%d",&n,&S);
48 memset(visit,0,sizeof(visit));
49 for(i=1; i<=n; i++)
50 {
51 c[i].v = i;
52 c[i].next = NULL;
53 }
54 for(i=1; i<n; i++)
55 {
56 scanf("%d%d",&a,&b);
57 connect(a,b);
58 connect(b,a);
59 }
60 visit[S] = 1;
61 father[S] = -1;
62 q.push(c[S]);
63 while( !q.empty() )
64 {
65 City p = q.front();
66 q.pop();
67 link = p.next;
68 while( link != NULL)
69 {
70 if( !visit[link->v] )
71 {
72 father[link->v] = p.v;
73 visit[link->v] = 1;
74 q.push(c[link->v]);
75 }
76 link = link->next;
77 }
78 }
79 while( !q.empty())
80 q.pop();
81 printf("%d",father[1]);
82 for(i=2; i<=n; i++)
83 {
84 printf(" %d",father[i]);
85 }
86 printf("\n");
87 for(i=1; i<=n; i++)
88 destory(&c[i]);
89 }
90 //system("pause");
91 return 0;
92 }