POJ 1655 Balancing Act (树的重心)
来源:互联网 发布:linux下如何编程 编辑:程序博客网 时间:2024/06/14 11:12
点击打开链接
题意:给出一棵树,求树的重心的编号,并且输出最大子树的节点数目。如果有最大节点数目相同的情况,选取重心编号较小的输出。
树的重心:找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心,删去重心后,生成的多棵树尽可能平衡。
比如样例,删除节点1,那么就会生成三棵子树,每个子树的节点数目都是2,这就是最平衡的情况了。如果多增加一条6 - 8的边,那么依然是选择删除节点1,生成三棵子树3 2 2也是最平衡的情况了。
求树的重心就是一遍dfs即可。
代码如下:
#include<iostream>#include<cstdio>#include<vector>#include<queue>#include<utility>#include<stack>#include<algorithm>#include<cstring>#include<string>#include<cmath>#include<set>#include<map>using namespace std;const int maxn = 2e4 + 5;int head[maxn], to[maxn << 1], nx[maxn << 1], tot;bool vst[maxn];int Min = 0x3f3f3f3f, key;int cnt[maxn], n; void add_edge(int u, int v) {to[tot] = v, nx[tot] = head[u], head[u] = tot++;swap(u, v);to[tot] = v, nx[tot] = head[u], head[u] = tot++;}int dfs(int u, int par) {cnt[u] = 1;int Max = 0;for(int i = head[u]; ~i; i = nx[i]) {int v = to[i];if(v != par) {cnt[u] += dfs(v, u);Max = max(Max, cnt[v]);}}if(Max < n - cnt[u])Max = n - cnt[u];if(Max < Min) {Min = Max;key = u;} else if(Max == Min && key > u) {key = u;}return cnt[u];}int main() {#ifndef ONLINE_JUDGE//freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);#endifint T;scanf("%d", &T);while(T--) {memset(head, -1, sizeof(head));tot = 0;Min = 0x3f3f3f3f;scanf("%d", &n);for(int i = 1, u, v; i < n; i++) {scanf("%d%d", &u, &v);add_edge(u, v);}dfs(1, 1);printf("%d %d\n", key, Min);}return 0;}
阅读全文
0 0
- POJ 1655 Balancing Act【树的重心】
- poj 1655 Balancing Act 【树的重心】
- POJ-1655 Balancing Act 树的重心
- 【POJ】1655 Balancing Act 树的重心
- 【树的重心】 POJ 1655 Balancing Act
- POJ 1655 Balancing Act 树的重心
- 【POJ 1655】Balancing Act 【树的重心】
- POJ 1655 Balancing Act 树的重心
- poj 1655 Balancing Act(树的重心)
- POJ 1655 Balancing Act (树的重心)
- poj 1655 Balancing Act 【树的重心】
- 【树的重心】 POJ 1655 Balancing Act
- POJ 1655 Balancing Act 树的重心
- poj 1655 Balancing Act【树的重心】
- poj 1655 Balancing Act(求树的重心)
- poj 1655 Balancing Act(求树的重心)
- POJ 题目1655 Balancing Act(树的重心)
- POJ 1655 Balancing Act (树的重心)
- eclipse中新建jsp页面报错The superclass "javax.servlet.http.HttpServlet" was not found on the Java Bui出错怎么解决
- 注销微信公众号
- 九度OJ题目1201:二叉排序树
- 51 nod 1279 扔盘子【思维】
- JAVA学习总结之List集合
- POJ 1655 Balancing Act (树的重心)
- 硬盘的读写原理------写得不错
- NOIP 2006 2^k进制数
- generate signed apk
- ITK和VTK比较
- 封装的一些 js, css使用小方法
- dmesg的详细用法
- [洛谷 1070]加分二叉树---树形DP
- linux 修改bash之PS1显示默认设置逐字详解-修改命令行显示风格