(POJ) 1741 Tree
程序员文章站
2022-05-12 15:57:43
...
点分治
解题思路:点分治模板题,看懂上面那篇博客就能切啦。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<cmath>
#include<sstream>
//#include<bits/stdc++.h>
#define il inline
#define pb push_back
#define fi first
#define se second
#define ms(_data,v) memset(_data,v,sizeof(_data))
#define sc(n) scanf("%d",&n)
#define SC(n,m) scanf("%d %d",&n,&m)
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define drep(i,a,b) for(int i=a;i>=b;--i)
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-9;
const int maxn=1e4+5;
int n,k,sz[maxn],root,mx,all,l,r;
ll dis[maxn],q[maxn],ans;
bool vis[maxn];
struct node{
int to,w;
};
vector<node> mp[maxn];
il void getroot(int x,int fa){ //获取重心
sz[x]=1;
int num=0;
for(int i=0;i<(int)(mp[x].size());++i){
int nto=mp[x][i].to;
if(vis[nto] || fa==nto) continue;
getroot(nto,x);
sz[x]+=sz[nto];
num=max(num,sz[nto]);
}
num=max(num,all-num);
if(num<mx){
mx=num;
root=x;
}
}
il void getdis(int x,int fa){ //源点到该分支各点的距离
q[++r]=dis[x];
for(int i=0;i<(int)(mp[x].size());++i){
int nto=mp[x][i].to,nw=mp[x][i].w;
if(nto==fa || vis[nto]) continue;
dis[nto]=dis[x]+nw;
getdis(nto,x);
}
}
il ll calc(int x,int v){ //计算满足的个数
r=0,l=1,dis[x]=v;
getdis(x,0);
ll sum=0;
sort(q+1,q+r+1);
while(l<r){
if(q[l]+q[r]<=k) sum+=r-l,l++;
else r--;
}
return sum;
}
il void dfs(int x){
ans+=calc(x,0);
vis[x]=1;
for(int i=0;i<(int)(mp[x].size());++i){
int nto=mp[x][i].to,nw=mp[x][i].w;
if(vis[nto]) continue;
ans-=calc(nto,nw); //减去不和条件的
all=sz[x];
mx=inf;
getroot(nto,0);
dfs(root);
}
}
int main(){
while(SC(n,k)!=EOF){
if(n==0 && k==0) break;
all=n,ans=0;
int x,y,z;
for(int i=1;i<=n-1;++i){
sc(x),sc(y),sc(z);
mp[x].pb(node{y,z});
mp[y].pb(node{x,z});
}
mx=inf;
getroot(1,0);
dfs(root);
cout<<ans<<endl;
for(int i=0;i<=n+5;++i){
mp[i].clear();
vis[i]=0;
}
}
return 0;
}
上一篇: CreateProcess