点分治

poj 1741

include

include

using namespace std;

define PA pair

const int N=10005,M=20005;
int read()
{
int s=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){s=(s<<1)+(s<<3)+ch-'0';ch=getchar();}
return s*f;
}
int n,m,ans;
int be[N],bn[M],bv[M],bl[M],bw=1;
int siz[M];
void put(int u,int v,int l)
{bw++;bn[bw]=be[u];be[u]=bw;bv[bw]=v;bl[bw]=l;}
int dfs(int e)
{
if(siz[e])return siz[e];
for(int i=be[bv[e]];i;i=bn[i])
if((i^e^1)&&bv[i])
siz[e]+=dfs(i);
siz[e]++;
return siz[e];
}
int q[N],q0[N];
void dfs2(int x,int dis,int fa,int q[])
{
q[++q[0]]=dis;
for(int i=be[x];i;i=bn[i])
if((i^fa^1)&&bv[i])
dfs2(bv[i],dis+bl[i],i,q);
}
void dfs3(int x,int fa)
{
for(int i=be[x];i;i=bn[i])
if((i^fa^1)&&bv[i])
siz[i^1]=0,dfs3(bv[i],i);
}
void fen(int x,int size)
{

for(int i=be[x];i;i=bn[i])
    if(dfs(i)*2>size&&bv[i]){
        fen(bv[i],size);
        return;
    }
q[0]=0;
dfs2(x,0,0,q);
sort(&q[1],&q[q[0]+1]);
for(int j=q[0],k=0;j>=1;j--)
    {while(q[k+1]+q[j]<=m&&k+1<=q[0])k++;
     ans+=k;
     }
for(int i=be[x];i;i=bn[i])
   {if(!bv[i])continue;
    q0[0]=0;
    dfs2(bv[i],bl[i],i,q0);
    sort(&q0[1],&q0[q0[0]+1]);
    for(int j=q0[0],k=0;j>=1;j--)
       {while(q0[k+1]+q0[j]<=m&&k+1<=q0[0])k++;
        ans-=k;//cout<<q0[j]<<" ";
       }//cout<<endl;
   }//cout<<"ans"<<ans<<endl;
for(int i=be[x];i;i=bn[i])
   if(bv[i])
     {bv[i^1]=0;
      dfs3(bv[i],0);
      fen(bv[i],dfs(i));
     }

}
int main()
{
while(1){
n=read();m=read();ans=0;
if(n==0)break;
for(int i=1;i<n;i++)
{int u=read(),v=read(),l=read();
put(u,v,l);
put(v,u,l);
}
for(int i=2;i<=bw;i++)
dfs(i);
fen(1,n);
printf("%d\n",(ans-n)/2);
for(int i=1;i<=n;i++)be[i]=0;
for(int i=2;i<=bw;i++)siz[i]=0;
bw=1;
}
return 0;
}

posted on 2017-09-16 08:55 wuyuhan 阅读(...) 评论(...) 编辑 收藏

导航

公告