Distance in Tree
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 %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):
给定一棵树,求有多少个点对之间的距离是k。
一开始的想法是,dfs处理出每个点的所有子树的距离为x的点,即cnt[x],然后就可以用cnt[i]*cnt[k-i],然后想着他和根节点也有关系,还要再计算一次和上面根节点的点对,然后要消去重复计算的点对,后来想了很久,也调了很久,仍然没有调出正确答案。
然后看了题解,发现不需要考虑和根节点的关系,只要考虑当前节点,一时间清醒过来,这样计算就没有重复的点对了。
AC代码:
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#define int long long
#define pi 3.14159265358979
using namespace std;
const int mod = 1e9+7;
const int N = 1e5+10;
const int INF = (1<<30)-1;
struct node{
vector<int> to;
int cnt[505]; // 记录所有距离不同的点的个数
}edge[N];
int k;
int ans = 0;
void dfs(int pos,int pre,int sum) // 第三个参数是深度,后来并没有用到。
{
int sz = edge[pos].to.size();
for(int j = 0 ; j < 505 ; j ++) edge[pos].cnt<