树的直径

思路:两个距离最长的点的距离,就是树的直径,每个人要走的距离,直径/2向上取整,就是(直径+1)/2;
代码实现:以一个有人的节点开始深搜,找到最远的有人的节点,再以这个节点为起点深搜,最远的点就是树的直径。
1
2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
struct Edge{
int v;
int next;
}edge[maxn*2];
int head[maxn];
int mark[maxn];
int n,m;
int num=1;
int ans = 0;
int pos;
void init(){
for(int i=1;i<=n;i++){
head[i] = -1;
}
}

void dfs(int now,int father,int d){
if(mark[now] && ans < d){
ans = d;
pos = now;
}
for(int i = head[now]; i != -1; i = edge[i].next){
if(edge[i].v == father) continue;
dfs(edge[i].v,now,d+1);
}
}

void addedge(int v,int u){
edge[num].v = v;
edge[num].next = head[u];
head[u] = num++;
}

int main(){
while(~scanf("%d%d",&n,&m)){
init();
int from,to;
for(int i=1;i<=n-1;i++){
scanf("%d%d",&from,&to);
addedge(from,to);
addedge(to,from);
}
// for(int u=1;u<=n;u++){
// for(int j = head[u]; j != -1; j = edge[j].next){
// cout<< u << " -> "<< edge[j].v <<endl;
// }
// }
int box;
for(int i=1;i<=m;i++){
scanf("%d",&box);
mark[box] = 1;
}
dfs(box,-1,0);
dfs(pos,-1,0);
cout<<(ans+1)/2<<endl;
}
}