标签:nyoj
1 10 1 1 9 1 8 8 10 10 3 8 6 1 2 10 4 9 5 3 7
-1 1 10 10 9 8 3 1 1 8
邻接表加dfs
01.
#include<iostream>
02.
#include<cstdio>
03.
#include<cstring>
04.
#include<vector>
05.
using
namespace
std;
06.
int
pre[100005];
07.
vector<
int
>v[100005];
08.
09.
void
DFS(
int
cur)
10.
{
11.
for
(
int
i
= 0; i < v[cur].size(); ++i)
12.
{
13.
if
(pre[v[cur][i]])
continue
;
//若存在父节点则继续遍历
14.
pre[v[cur][i]]
= cur;
//相连节点的父节点为cur
15.
DFS(v[cur][i]);
//深搜到底,把一条路上父节点全部找出
16.
}
17.
}
18.
19.
int
main()
20.
{
21.
int
ncase,
num, cur, i, x, y;
22.
scanf
(
"%d"
,
&ncase);
23.
while
(ncase--)
24.
{
25.
memset
(v,
0,
sizeof
(v));
26.
memset
(pre,
0,
sizeof
(pre));
27.
scanf
(
"%d%d"
,
&num, &cur);
28.
pre[cur]
= - 1;
//起点没有父节点
29.
for
(i
= 0; i < num - 1; ++i)
30.
{
31.
scanf
(
"%d%d"
,
&x, &y);
32.
v[x].push_back(y);
//x与y相连
33.
v[y].push_back(x);
//y与x也肯定相连
34.
}
35.
DFS(cur);
//起点开始深搜
36.
for
(i
= 1; i <= num; ++i)
37.
printf
(
"%d
"
,
pre[i]);
//每个节点的父节点都保存在pri数组,输出即可
38.
}
39.
return
0;
40.
}
标签:nyoj
原文地址:http://blog.csdn.net/justesss/article/details/38045139