A tree is a connected graph that doesn’t contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs ( v, u) and ( u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as " a i b i" (without the quotes) (1 ≤ a i, b i ≤ n, a i ≠ b i), where a i and b i are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree’s vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
思路:看来我这榆木脑子真的不适合做dp。。
我们令dp[u][i]代表的是子树中距离u点为i的点的个数。每一次求出一个分支来,就利用当前父节点已有的点和这次求出来的点,找寻符合条件的。然后再将这次求出来的点更新到父节点上去。具体看代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxx=5e4+100;
struct edge{
int to,next;
}e[maxx<<1];
int head[maxx<<1];
int dp[maxx][501];
int n,k,tot;
inline void init()
{
tot=0;
memset(head,-1,sizeof(head));
for(int i=0;i<=n;i++)
for(int j=0;j<=k;j++) dp[i][j]=0;
}
inline void add(int u,int v)
{
e[tot].next=head[u],e[tot].to=v,head[u]=tot++;
}
inline void dfs(int u,int f,ll &ans)
{
dp[u][0]=1;
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].to;
if(to==f) continue;
dfs(to,u,ans);
for(int j=0;j<k;j++) ans+=dp[u][j]*dp[to][k-j-1];
for(int j=1;j<=k;j++)
{
if(dp[to][j-1]) dp[u][j]+=dp[to][j-1];
else break;
}
}
}
int main()
{
scanf("%d%d",&n,&k);
init();
int x,y;
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
if(k==1)
{
cout<<n-1<<endl;
return 0;
}
ll ans=0;
dfs(1,0,ans);
cout<<ans<<endl;
return 0;
}