poj1655 求树的重心
来源:互联网 发布:单片机51交通灯程序 编辑:程序博客网 时间:2024/05/21 11:21
题目链接:http://poj.org/problem?id=1655
题意:求树的重心。
解法:对树进行dfs,记录对于某个节点它的子树大小son[u],在dfs的时候可以处理出来这个点的所有子树节点个数的最大值Max,而n-son[u]可以处理出它父节点延伸出去的节点数目,那么答案便可以找到了。
#include<cstdio>#include<cstring>#include<algorithm>#define inf 10000000using namespace std;const int N=20005;int head[N],top=0;int n;int son[N];int ans,point;struct Edge{ int v,next;}edge[N*2];void init(){ memset(head,-1,sizeof(head)); top=0; memset(son,0,sizeof(son)); ans=inf;}void addedge(int u,int v){ edge[top].v=v; edge[top].next=head[u]; head[u]=top++;}void dfs(int u,int fa){ son[u]=1; int Max=0; for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; if(v==fa)continue; dfs(v,u); son[u]+=son[v]; Max=max(Max,son[v]); } int tmp=max(Max,n-son[u]); if(tmp<ans||tmp==ans&&u<point){ ans=tmp; point=u; }}int main(){ int T; scanf("%d",&T); while(T--) { init(); scanf("%d",&n); int u,v; for(int i=1;i<n;i++){ scanf("%d%d",&u,&v); addedge(u,v); addedge(v,u); } dfs(1,-1); printf("%d %d\n",point,ans); } return 0;}
0 0
- poj1655 求树的重心
- 树形dp求树的重心 poj1655
- 求树的重心(POJ1655)
- 【poj1655】【poj3107】【求树的重心】
- POJ1655 Balancing Act 求树的重心
- 【poj1655】Balancing Act 求树的重心
- poj1655树的重心
- poj1655(树的重心)
- poj1655(树的重心)
- POJ1655 Balancing Act (树的重心)
- 【POJ1655】Balancing Act【树的重心】
- 树的重心POJ1655 Balancing Act
- poj1655—Balancing Act(树的重心)
- [POJ1655]Balancing Act(树的重心)
- poj1655 Balancing Act(树的重心[模板])
- 树重心 poj1655 Balancing Act
- POJ1655 Balancing Act——树的重心,Dfs
- poj1655 Balancing Act【树的重心+树形dp】
- Android自定义View笔记
- 数的读法
- c++ 与 构造函数
- SQLServer锁的概述
- 绘图级的动画
- poj1655 求树的重心
- 单例模式封装简单的拖拽
- Major GC和Full GC的区别以及触发条件
- JAVA设计模式--单例模式
- 微信企业号的消息发送
- 70.Failed to install Safe.apk on device 'emulator-5554': timeout问题解决方法
- Android数据库框架greenDao学习笔记(二)---注解
- 嵌入式面试题——ARM试题(一)
- tcpip基础一