复制代码
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
66
67
68
69
70
71**2207 - 树的中心 **来源: 东方博宜oj oj.czos.cn **思路:先求树的直径,再求直径的中间点(即中心) #include<bits/stdc++.h> using namespace std; const int N=1e5+10; int n,x,y,k; int fa[N],dep[N],pre[N]; struct node { int from,to,next; }a[N*2]; // N*2的原因:无向图 void add(int u,int v) { ++k; a[k].from=u; a[k].to=v; a[k].next=pre[u]; pre[u]=k; } // 深搜求父子关系及深度 void dfs(int x,int f) { fa[x]=f; dep[x]=dep[f]+1; for(int i=pre[x];i!=0;i=a[i].next) { if(a[i].to!=f) dfs(a[i].to,x); } } int main() { cin>>n; for(int i=1;i<=n-1;i++) { cin>>x>>y; add(x,y); add(y,x); } dfs(1,0); x=1; for(int i=2;i<=n;i++) { if(dep[i]>dep[x]) x=i; } dfs(x,0); y=1; for(int i=2;i<=n;i++) { if(dep[i]>dep[y]) y=i; } // 此时x和y是直径的两个端点 int d=dep[y]; if(d%2) //如果深度为奇数,中心点有一个 { for(int i=1;i<=d/2;i++) y=fa[y]; cout<< y; } else //如果深度为偶数,中心点有两个 { for(int i=1;i<=d/2-1;i++) y=fa[y]; if(y<fa[y]) cout<< y<< " "<< fa[y]; else cout<< fa[y]<< " "<< y; } return 0; }
最后
以上就是忧虑太阳最近收集整理的关于2207 - 树的中心的全部内容,更多相关2207内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复