-
M - Godfather
- POJ - 3107
- 树的重心也叫树的质心。找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心,删去重心后,生成的多棵树尽可能平衡。
- Based on the idea that Godfather wants to have the most possible control over mafia, the chief of the police has made a suggestion that Godfather is such a person that after deleting it from the communications tree the size of the largest remaining connected component is as small as possible. Help the police to find all potential Godfathers and they will arrest them.
- 基于教父想要对黑手党进行尽可能多的控制的想法,警察局长建议教父是这样的人,在从通信树中删除它之后,剩下的最大的连接部件的尺寸尽可能小。帮助警察找到所有潜在的教父,他们会逮捕他们。
-
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define maxn 50005 #define inf 0x3f3f3f3f struct node { int v,to; } edge[maxn*2]; int head[maxn]; int cnt,x,y,n; int dp[maxn],num; int ans[maxn],sum; void add(int u,int v) { edge[++cnt].to=head[u]; edge[cnt].v=v; head[u]=cnt; edge[++cnt].to=head[v]; edge[cnt].v=u; head[v]=cnt; } void dfs(int u,int pre) { dp[u]=1; int temp=0; for(int i=head[u]; i!=-1; i=edge[i].to) { int v=edge[i].v; if(v==pre)continue; dfs(v,u); dp[u]+=dp[v]; temp=max(temp,dp[v]); } temp=max(temp,n-dp[u]); if(temp<sum) { sum=temp; num=0; ans[++num]=u; } else if(temp==sum) ans[++num]=u; } int main() { sum=inf; scanf("%d",&n); memset(head,-1,sizeof(head)); for(int i=1; i<n; i++) { scanf("%d%d",&x,&y); add(x,y); } dfs(1,0); sort(ans+1,ans+num+1); for(int i=1; i<num; i++) printf("%d ",ans[i]); printf("%d\n",ans[num]); return 0; }
M - Godfather POJ - 树的重心
最新推荐文章于 2021-02-15 16:51:23 发布