POJ 1655 (树dp or 树重心)
来源:互联网 发布:python调用caffe测试 编辑:程序博客网 时间:2024/06/01 11:15
【题意】不解释了。
【解题方法】其实这题就是一个树的重心,我用两种方法写的,水题。
【AC 代码 1】
//树的重心#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 20005;const int inf = 0x3f3f3f3f;int head[maxn],tot,mx,mxcnt,n,siz[maxn];int minn,minid;void init(){ memset(head,-1,sizeof(head)); tot=0;}struct edge{ int v,next;}E[maxn*2];void addedge(int u,int v){ E[tot].v=v,E[tot].next=head[u],head[u]=tot++;}void dfs(int u,int fa){ siz[u]=1; int he=-1; for(int i=head[u]; ~i; i=E[i].next){ int v=E[i].v; if(v==fa) continue; dfs(v,u); siz[u]+=siz[v]; he=max(he,siz[v]); } he=max(he,n-siz[u]); if(he<minn){ minn=he; minid=u; }else if(he==minn&&minid<u){ minid=u; } return ;}int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d",&n); int u,v; init(); for(int i=1; i<n; i++){ scanf("%d%d",&u,&v); addedge(u,v); addedge(v,u); } minn=inf; dfs(1,-1); cout<<minid<<" "<<minn<<endl; } return 0;}
【AC代码2】
//树形do#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 20010;int head[maxn],tot,dp[maxn],siz[maxn],n;struct edge{ int v,next;}E[maxn*2];void init(){ memset(head,-1,sizeof(head)); tot=0;}void addedge(int u,int v){ E[tot].v=v,E[tot].next=head[u],head[u]=tot++;}void dfs(int u,int fa){ siz[u]=1,dp[u]=0; for(int i=head[u]; ~i; i=E[i].next){ int v=E[i].v; if(v==fa) continue; dfs(v,u); dp[u]=max(dp[u],siz[v]); siz[u]+=siz[v]; } dp[u]=max(dp[u],n-siz[u]);}int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d",&n); init(); for(int i=1; i<n; i++){ int u,v; scanf("%d%d",&u,&v); addedge(u,v); addedge(v,u); } dfs(1,-1); int ans1=1,ans2=dp[1]; for(int i=2; i<=n; i++){ if(dp[i]<ans2){ ans2=dp[i]; ans1=i; } } cout<<ans1<<" "<<ans2<<endl; }}
0 0
- POJ 1655 (树dp or 树重心)
- POJ 1655 树的重心(树形 DP)
- 求树的重心 POJ 1655、POJ 3107 树形DP
- POJ 1655 - DP 树的重心,经典 #P
- poj 1655 树形dp求取树的重心
- POJ 1655 Balancing Act(求树的重心--树形DP)
- POJ 1655 Balancing Act (树形dp 树的重心)
- poj-1655-Balancing Act 树形dp/树的重心
- poj 1655 Balancing Act 【树形DP 求树的重心】
- POJ 1655 Balancing Act 树型DP 树的重心 板题
- poj 1655 Balancing Act(树的重心,树形dp)
- POJ.1655 Balancing Act (树形DP 树的重心)
- Poj 1655(树的重心、树形DP、经典)
- poj 3107 Godfather(树形dp,树的重心)
- POJ 1655 树的重心
- poj 1655 树的重心
- poj 1655 树的重心
- poj-1655 树的重心
- POJ 2409 Let it Bead (Polya) .
- 随手整理
- css left/right拉伸和width同时存在
- ios-正则表达式
- hdu4725——The Shortest Path in Nya Graph(SPFA+两层图)
- POJ 1655 (树dp or 树重心)
- kali 2.0中metasploit的使用教程
- Universal-Image-Loader源码阅读(8)-core/imageaware/NonViewAware
- poj1328 贪心
- 2016.8.15 夏令营 Day15
- CALayer&Core Animation核心动画
- Picasso获取得到的Bitmap
- codeforces 510.B Fox And Two Dots (DFS好题)
- python数据持久存储:pickle模块的基本使用