[题解] POJ 3107 Godfather(树型DP 求树的直径)

  题意:给你一棵有n个节点的树,删除一个节点,使删除该点后所形成的森林中节点数最多的树尽可能小,可能有多种方案,按编号顺序输出。
  分析:这道题是裸的树的重心题,那么我们就查找每一个节点的子树大小,不难发现  num[i]=num[son[i]] n u m [ i ] = ∑ n u m [ s o n [ i ] ] ,然后我们需要保存每一个点删除后最大树的大小  ans[i] a n s [ i ] ,仍然不难发现  ans[i]=max(num[son[i]]) a n s [ i ] = m a x ( n u m [ s o n [ i ] ] ) ,最后利用一个小小的技巧,即时保存在答案数组中,具体请看代码。
  详细代码如下:

#include <bits/stdc++.h>
using namespace std;
int frist[50010];
int net[100010];
int c[100010];
int num[50010];
int ans[50010];
int maxn=10000000;
int total=0,n;
bool tot[50010];
int read() {
    int ans=0,flag=1;
    char ch=getchar();
    while( (ch>'9' || ch<'0') && ch!='-' ) ch=getchar();
    if(ch=='-') flag=-1,ch=getchar();
    while(ch>='0' && ch<='9') ans=ans*10+ch-'0',ch=getchar();
    return ans*flag;
}
void addedge(int x,int y) {//邻接表保存
    c[++total]=y;
    net[total]=frist[x];
    frist[x]=total;
    c[++total]=x;
    net[total]=frist[y];
    frist[y]=total;
}
void work(int son,int fa) {
    for(int i=frist[son];i;i=net[i]) {
        if(c[i]!=fa) {
            work(c[i],son);
            num[son]+=num[c[i]];
            if(num[c[i]]>ans[son]) ans[son]=num[c[i]];
        }
    }
    ans[son]=max(ans[son],n-num[son]);//由于我们并没有加入父亲那边的树,所以我们需要比较一下
    //储存答案技巧
    if(ans[son]<maxn) maxn=ans[son],memset(tot,0,sizeof(tot)),tot[son]=1;
    else if(ans[son]==maxn) tot[son]=1;
    return ;
}
int main() {
    int i;
    n=read();
    for(i=1;i<=n;i++) {
        num[i]=1;
    }
    for(i=1;i<n;i++) {
        addedge(read(),read());
    }
    work(1,0);
    for(i=1;i<=n;i++) {
        if(tot[i]) printf("%d ",i);
    }
    return 0;
}

                                    by:Chlience

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值