fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define int long long
  5.  
  6. const int N = 200005;
  7.  
  8. int n, k, ans;
  9. vector<int> adj[N];
  10.  
  11. map<int,int>* dfs(int u, int p) {
  12.  
  13. auto *mp = new map<int,int>();
  14. (*mp)[0] = 1;
  15.  
  16. for (int v : adj[u]) {
  17.  
  18. if (v == p) continue;
  19.  
  20. auto *child = dfs(v, u);
  21.  
  22. // luôn merge nhỏ vào lớn
  23. if (mp->size() < child->size())
  24. swap(mp, child);
  25.  
  26. // đếm đáp án
  27. for (auto [d, f] : *child) {
  28.  
  29. int need = k - d - 1;
  30.  
  31. if (mp->count(need))
  32. ans += 1LL * f * (*mp)[need];
  33. }
  34.  
  35. // merge
  36. for (auto [d, f] : *child) {
  37. (*mp)[d + 1] += f;
  38. }
  39. }
  40.  
  41. return mp;
  42. }
  43.  
  44. signed main() {
  45.  
  46. ios::sync_with_stdio(false);
  47. cin.tie(nullptr);
  48.  
  49. cin >> n >> k;
  50.  
  51. for (int i = 1; i < n; i++) {
  52. int u, v;
  53. cin >> u >> v;
  54.  
  55. adj[u].push_back(v);
  56. adj[v].push_back(u);
  57. }
  58.  
  59. dfs(1, 0);
  60.  
  61. cout << ans;
  62. }
Success #stdin #stdout 0.01s 8172KB
stdin
Standard input is empty
stdout
Standard output is empty