POJ 1741 树分治

思路:
http://blog.sina.com.cn/s/blog_6d5aa19a0100o73m.html

//By SiriusRen
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 20005
int n,k,xx,yy,zz,first[N],next[N],v[N],w[N],tot;
int deep[N],ans,root,size[N],f[N],vis[N],sum,d[N];
void add(int x,int y,int z){w[tot]=z,v[tot]=y,next[tot]=first[x],first[x]=tot++;}
void getroot(int x,int fa){
    size[x]=1,f[x]=0;
    for(int i=first[x];~i;i=next[i])if(!vis[v[i]]&&v[i]!=fa){
        getroot(v[i],x);
        size[x]+=size[v[i]];
        f[x]=max(f[x],size[v[i]]);
    }
    f[x]=max(f[x],sum-f[x]);
    if(f[x]<f[root])root=x;
}
void getdeep(int x,int fa){
    deep[++deep[0]]=d[x];
    for(int i=first[x];~i;i=next[i])
        if(!vis[v[i]]&&v[i]!=fa&&d[x]+w[i]<=k)
            d[v[i]]=d[x]+w[i],getdeep(v[i],x);
}
int calc(int x,int now){
    d[x]=now,deep[0]=0,getdeep(x,0);
    sort(deep+1,deep+deep[0]+1);
    int t,l,r;
    for(t=0,l=1,r=deep[0];l<r;)
        if(deep[l]+deep[r]<=k)t+=r-l,l++;
        else r--;
    return t;
}
void work(int x){
    ans+=calc(x,0),vis[x]=1;
    for(int i=first[x];~i;i=next[i])if(!vis[v[i]]){
        ans-=calc(v[i],w[i]),sum=size[v[i]];
        root=0,getroot(v[i],root),work(root);
    }
}
int main(){
    while(scanf("%d%d",&n,&k)&&(n||k)){
        memset(first,-1,sizeof(first));
        memset(vis,0,sizeof(vis));
        f[0]=10005,root=ans=tot=0,sum=n;
        for(int i=1;i<n;i++){
            scanf("%d%d%d",&xx,&yy,&zz);
            add(xx,yy,zz),add(yy,xx,zz);
        }
        getroot(1,0),work(root);
        printf("%d\n",ans);
    }
}

这里写图片描述

posted @ 2017-01-12 17:59  SiriusRen  阅读(110)  评论(0编辑  收藏  举报