POJ 1741

第一次写点分治,感觉写得好挫TAT。

调了半个小时,各种坑细节,唉,不谈了。

这代码果断不能当模板用,太坑了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=10005;
const int inf=1e9;
int root,sz,mi,mx[N];
int n,k;
int d[N],tot,ans,siz[N];
struct Edge{int to,next,v;}e[N*2];
int head[N],cnt;
bool vis[N];
void ins(int u,int v,int w){
	e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].v=w;
}
void getroot(int u,int fa){
	siz[u]=1,mx[u]=0;
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;
		if(v==fa||vis[v])continue;
		getroot(v,u);
		siz[u]+=siz[v];
		mx[u]=max(mx[u],siz[v]);
	}
	mx[u]=max(mx[u],sz-siz[u]);
	if(mx[u]<mi)mi=mx[u],root=u;
}
void getdep(int u,int fa,int depth){
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;
		if(v==fa||vis[v])continue;
		d[++tot]=depth+e[i].v;
		getdep(v,u,depth+e[i].v);
	}
}
int calc(){
	int res=0;
	sort(d+1,d+1+tot);
	for(int i=1,j=tot;i<j;i++){
		while(i<j&&d[i]+d[j]>k)j--;
		if(i>=j)break;
		res+=j-i;
	}
	return res;
}
void solve(int u){
	mi=inf;
	getroot(u,u);vis[root]=true;
	u=root;tot=0;getdep(u,u,0);
	for(int i=1;i<=tot;i++)if(d[i]<=k)ans++;
	int A=calc(),B=0;
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;
		if(vis[v])continue;
		tot=0;getdep(v,u,e[i].v);d[++tot]=e[i].v;B+=calc();
	}
	ans+=A-B;
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;
		if(vis[v])continue;
		sz=siz[v];
		solve(v);
	}
}
int main(){
	while(scanf("%d%d",&n,&k)&&n&&k){
		sz=n;int u,v,w;cnt=0;
		memset(vis,false,sizeof(vis));
		memset(head,0,sizeof(head));
		for(int i=1;i<n;i++){
			scanf("%d%d%d",&u,&v,&w);
			ins(u,v,w);ins(v,u,w);
		}
		ans=0;
		solve(1);
		printf("%d\n",ans);
	}
	return 0;
}
	


你可能感兴趣的:(POJ 1741)