题意:
求一颗树上长度不超过k的路径。
题解:
点分治模板。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,int> pii;
streambuf *ib,*ob;
inline int read()
{
char ch=ib->sbumpc();int i=0,f=1;
while(!isdigit(ch)){if(ch=='-')f=-1;ch=ib->sbumpc();}
while(isdigit(ch)){i=(i<<1)+(i<<3)+ch-'0';ch=ib->sbumpc();}
return i*f;
}
inline void W(int x)
{
static int buf[50];
if(!x){ob->sputc('0');return;}
if(x<0){ob->sputc('-');x=-x;}
while(x){buf[++buf[0]]=x%10;x/=10;}
while(buf[0])ob->sputc(buf[buf[0]--]+'0');
}
const int Maxn=1e4+50;
int n,k,G,vis[Maxn],dis[Maxn],total,mx,len[Maxn],cnt,ans,sze[Maxn];
vector<pii>edge[Maxn];
inline void getdep(int now,int dist,int f)
{
len[++cnt]=dist;sze[now]=1;
for(int e=edge[now].size()-1;e>=0;e--)
{
int v=edge[now][e].first;
if(v==f||vis[v])continue;
getdep(v,dist+edge[now][e].second,now);
sze[now]+=sze[v];
}
}
inline int calc(int now,int dis)
{
int res=0;len[cnt=1]=dis;
for(int e=edge[now].size()-1;e>=0;e--)
{
int v=edge[now][e].first;
if(vis[v])continue;
getdep(v,dis+edge[now][e].second,now);
}
sort(len+1,len+cnt+1);
int l=1,r=cnt;
while(l<r)
{
if(len[l]+len[r]<=k)res+=r-l,l++;
else r--;
}
return res;
}
inline void findG(int now,int f=0)
{
sze[now]=1;int mxnow=0;
for(int e=edge[now].size()-1;e>=0;e--)
{
int v=edge[now][e].first;
if(v==f||vis[v])continue;
findG(v,now);
mxnow=max(mxnow,sze[v]);
sze[now]+=sze[v];
}
mxnow=max(mxnow,total-sze[now]);
if(mxnow<mx)mx=mxnow,G=now;
}
inline void solve(int now)
{
vis[now]=1;
ans+=calc(G,0);
for(int e=edge[now].size()-1;e>=0;e--)
{
int v=edge[now][e].first;
if(vis[v])continue;
ans-=calc(v,edge[now][e].second);
}
for(int e=edge[now].size()-1;e>=0;e--)
{
int v=edge[now][e].first;
if(vis[v])continue;
total=mx=sze[v];
findG(v);
solve(G);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ib=cin.rdbuf();ob=cout.rdbuf();
while(n=read(),k=read(),n,k)
{
ans=0;
for(int i=1;i<=n;i++)edge[i].clear(),vis[i]=0;
for(int i=1;i<n;i++)
{
int x=read(),y=read(),z=read();
edge[x].push_back(make_pair(y,z));
edge[y].push_back(make_pair(x,z));
}
total=mx=n;
findG(1,0);
solve(G);
W(ans);ob->sputc('\n');
}
}