1.
import
java.util.ArrayDeque;
02.
import
java.util.Queue;
03.
import
java.util.Scanner;
04.
05.
public
class
Main
{
06.
07.
public
static
final
int
N
= 100001;
08.
public
static
Vertex[]
list =
new
Vertex[N];
09.
public
static
int
[]
tag;
10.
11.
public
static
void
main(String[]
args) {
12.
Scanner
sc =
new
Scanner(System.in);
13.
int
caseCount
= sc.nextInt();
14.
while
(caseCount--
> 0) {
15.
int
vertexCount
= sc.nextInt();
16.
tag
=
new
int
[vertexCount+1];
17.
int
startVertex
= sc.nextInt();
18.
init(vertexCount);
19.
for
(
int
i=1;
i<vertexCount; i++) {
20.
int
v1
= sc.nextInt();
21.
int
v2
= sc.nextInt();
22.
insertList(v1,
v2);
23.
}
24.
search(startVertex);
25.
show();
26.
}
27.
}
28.
29.
private
static
void
show()
{
30.
for
(
int
i=1;
i<tag.length-1; i++) {
31.
System.out.print(tag[i]
+
"
"
);
32.
}
33.
System.out.println(tag[tag.length-1]);
34.
}
35.
36.
private
static
void
search(
int
startVertex)
{
37.
Queue<Vertex>
queue =
new
ArrayDeque<Vertex>();
38.
queue.add(
new
Main().
new
Vertex(startVertex,
null));
39.
Vertex
temp;
40.
int
parent;
41.
tag[startVertex]
= -1;
42.
while
(!queue.isEmpty())
{
43.
parent
= queue.poll().vertex;
44.
temp
= list[parent];
45.
while
(temp
!= null) {
46.
if
(tag[temp.vertex]
== 0) {
47.
tag[temp.vertex]
= parent;
48.
queue.add(temp);
49.
}
50.
temp
= temp.link;
51.
}
52.
}
53.
}
54.
55.
private
static
void
insertList(
int
v1,
int
v2)
{
56.
list[v1]
=
new
Main().
new
Vertex(v2,
list[v1]);
57.
list[v2]
=
new
Main().
new
Vertex(v1,
list[v2]);
58.
}
59.
60.
private
static
void
init(
int
vertexCount)
{
61.
for
(
int
i=1;
i<=vertexCount; i++) {
62.
list[i]
= null;
63.
}
64.
}
65.
66.
class
Vertex
{
67.
int
vertex;
68.
Vertex
link;
69.
70.
public
Vertex(
int
vertex,
Vertex link) {
71.
this
.vertex
= vertex;
72.
this
.link
= link;
73.
}
74.
}
75.
76.
}