模板_点分治

struct Node{int v,l;};vector g[N];
int n,k,ans,sz,root,s[N],d[N],f[N];
bool b[N];vector<int> deep;
void GetRoot(int u,int fa){
    s[u]=1,f[u]=0;int lim=g[u].size();
    for(int i=0,v;iif((v=g[u][i].v)!=fa&&!b[v])
            GetRoot(v,u),s[u]+=s[v],f[u]=max(f[u],s[v]);
    f[u]=max(f[u],sz-s[u]);if(f[u]void GetDeep(int u,int fa){
    deep.push_back(d[u]),s[u]=1;int lim=g[u].size();
    for(int i=0,v;iif((v=g[u][i].v)!=fa&&!b[v])
            d[v]=d[u]+g[u][i].l,GetDeep(v,u),s[u]+=s[v];
}
int Calc(int u,int w,int res=0){
    deep.clear(),d[u]=w;GetDeep(u,0);
    sort(deep.begin(),deep.end());
    for(int l=0,r=deep.size()-1;lif(deep[l]+deep[r]<=k) res+=r-l,l++;
        else r--;
    return res;
}
void GetAns(int u){
    ans+=Calc(u,0),b[u]=1;int lim=g[u].size();
    for(int i=0,v;iif(!b[v=g[u][i].v])
            ans-=Calc(v,g[u][i].l),f[0]=sz=s[u],
            GetRoot(v,root=0),GetAns(root);
}

你可能感兴趣的:(分治,点分治,模板)