题目链接:http://codeforces.com/problemset/problem/161/D
D. Distance in Tree
time limit per test
3 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output
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 "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi 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 %I64dspecifier.
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).
题意:求树上长度恰好为K的路径个数
解题思路:dp[i][j]表示,以i为根结点、长度为j的子树的个数。以x为根结点,选取两棵子树作为它的左右子树,先选出一个子结点y作为它的左子树,设左子树的长度为j,那么他的右子树的长度为k-j-2,再加上根结点到左右子树的距离2,总和等于k。其中0<=j<=min(depth[x],k-2)。左子树y的的个数等于dp[y][j],右子树的个数等于dp[x][k-j-1]-dp[y][k-j-2],也就是以x为根结点所有长度为k-j-1的子树减去以y为根结点长度为k-j-2的子树,这样是为了防止路径重合,然后总数除以2。最后再加上以i为根结点,长度为k的子树的个数,其中1<=i<=n。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
#define LL long long
#define N 50005
#define K 502
int dp[N][K+3];
vector<int>g[N];
bool vis[N];
int depth[N], fa[N];
int n, k;
void dfs(int x){
vis[x]=1;
dp[x][0]=1;
int y;
for(int i=0;i<g[x].size();++i){
y=g[x][i];
if(vis[y]) continue;
fa[y]=x;
dfs(y);
depth[x]=max(depth[y]+1,depth[x]);
int tmp=min(depth[y],K-1);
for(int j=0;j<=tmp;++j){
dp[x][j+1]+=dp[y][j];
}
}
}
int main()
{
int u, v;
scanf("%d%d",&n,&k);
for(int i=1;i<n;++i){
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1);
LL ans=0;
int tmp;
for(int x=1;x<=n;++x){
int y;
for(int i=0;i<g[x].size();++i){
y=g[x][i];
if(y==fa[x]) continue;
int tmp=min(k-2,depth[y]);
for(int j=0;j<=tmp;++j){
ans+=dp[y][j]*(dp[x][k-j-1]-dp[y][k-j-2]);
}
}
}
ans/=2;
for(int i=1;i<=n;++i) ans+=dp[i][k];
cout<<ans;
return 0;
}