POJ1741 Tree (树形dp+点分治)

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
题意:有一棵树,每条边多有一个边权,问你有多少对(u,v)满足dis(u,v)<= k
粘点重心相关知识,与本题无关,树的重心的一些性质:
1.树中所有点到某个点的距离和中,到重心的距离和是最小的;如果有两个重心,那么他们的距离和一样。
2.把两个树通过一条边相连得到一个新的树,那么新的树的重心在连接原来两个树的重心的路径上。
3.把一个树添加或删除一个叶子,那么它的重心最多只移动一条边的距离。
#include
#include
#include
using namespace std;
#define maxn 10010
#define inf 1e8
int p[maxn],num;
struct node
{
    int u,v,len,next;
    node() {}
    node(int u,int v,int len,int next): u(u),v(v),len(len),next(next) {}
}E[maxn*2];
void init()
{
    num=0;
    memset(p,-1,sizeof(p));
}
void add(int u,int v,int len)
{
    E[num]=node(u,v,len,p[u]);
    p[u]=num++;
}
int n,k;
int ans;
int si[maxn],maxx[maxn],dis[maxn];
bool use[maxn];
int root;
int mm,cnt;
void dfs_size(int u,int fa)
{
    si[u]=1;
    maxx[u]=0;
    for(int i=p[u];~i;i=E[i].next)
    {
        int v=E[i].v;
        if(v==fa||use[v]) continue;
        dfs_size(v,u);
        si[u]+=si[v];
        maxx[u]=max(maxx[u],si[v]);
    }
}
void dfs_root(int id,int u,int fa)///找出重心
{
    if(si[id]-si[u]>maxx[u]) maxx[u]=si[id]-si[u];
    if(maxx[u]k&&l

你可能感兴趣的:(DP)