POJ1741:树的点分治

Tree

Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 31781   Accepted: 10615

Description

Give a tree with n vertices,each edge has a length(positive integer less than 1001). 
Define dist(u,v)=The min distance between node u and v. 
Give an integer k,for every pair (u,v) of vertices is called valid if and only if dist(u,v) not exceed k. 
Write a program that will count how many pairs which are valid for a given tree. 

Input

The input contains several test cases. The first line of each test case contains two integers n, k. (n<=10000) The following n-1 lines each contains three integers u,v,l, which means there is an edge between node u and v of length l. 
The last test case is followed by two zeros. 

Output

For each test case output the answer on a single line.

Sample Input

5 4
1 2 3
1 3 1
1 4 2
3 5 1
0 0

Sample Output

8

题解:点分治模板题,求树上距离不大于k的点的对数

#include <bits/stdc++.h>
using namespace std;
int const N = 10000 + 10;
int const inf = 0x7f7f7f7f;
int n,k,tot,root,Val;
int ans,mav[N],size[N],num[N];
int val[2*N],first[N],ne[2*N],to[2*N];
bool vis[N];
void add(int x,int y,int dis){
	ne[++tot] = first[x];
	to[tot] = y;
	val[tot] = dis;
	first[x] = tot;
}
void Init(){
	tot = 0;
	memset(first,0,sizeof(first));
	memset(vis,false,sizeof(vis));
	for(int i=1;i<=n-1;i++){
		int x,y,dis;
		scanf("%d%d%d",&x,&y,&dis);
		add(x,y,dis);	add(y,x,dis);
	}
	ans = 0;
}
void Get_Size(int x,int fa){
	size[x] = 1,mav[x] = 0;
	for(int i=first[x];i;i=ne[i]){
		int u = to[i];
		if(u == fa || vis[u])	continue;  
		Get_Size(u,x);
		size[x] += size[u];
		mav[x] = max(mav[x],size[u]);
	}
}
void Get_Root(int sz,int x,int fa){
	mav[x] = max(size[sz] - size[x],mav[x]);
	if(mav[x] < Val){
		Val = mav[x];
		root = x;
	}
	for(int i=first[x];i;i=ne[i]){
		int u = to[i];
		if(u == fa || vis[u])	continue;
		Get_Root(sz,u,x);
	}
}
void Get_Dis(int x,int fa,int dis){
	num[++tot] = dis;
	for(int i=first[x];i;i=ne[i]){
		if(to[i] == fa || vis[to[i]])	continue;
		Get_Dis(to[i],x,dis+val[i]);
	}
}
int cacl(int x,int dis){
	int now = 0;tot = 0;
	Get_Dis(x,0,dis);
	sort(num+1,num+1+tot);
	for(int i=1,j=tot;i<j;i++){
		while(num[i]+num[j]>k && i<j)	j--;
		now += (j-i);
	}
	return now;
}
void DFS(int x){
	Val = inf;
	Get_Size(x,0);
	Get_Root(x,x,0);
	ans += cacl(root,0);
	vis[root] = true;	
	for(int i=first[root];i;i=ne[i]){
		if(!vis[to[i]]){
			ans -= cacl(to[i],val[i]);
			DFS(to[i]);
		}
	}
}
int main(){
	while(cin>>n>>k){
		if(!n && !k)	return 0;
		Init();
		DFS(1);
		printf("%d\n",ans);
	}
}

 

posted @ 2019-02-07 11:28  月光下の魔术师  阅读(12)  评论(0)    收藏  举报