Advertisement
Guest User

Untitled

a guest
May 23rd, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. typedef long long ll;
  5. int n, k;
  6.  
  7. vector<int> g[100100];
  8. int sz[100100];
  9. int lev[100100];
  10. int mx[100100];
  11. int u[100100];
  12. vector<int> G;
  13.  
  14. void dfs(int v, int pa){
  15. sz[v] = 1;
  16. mx[v] = 0;
  17. lev[v] = lev[pa] + 1;
  18. for(int to: g[v]){
  19. if(u[to]) continue;
  20. if(to == pa) continue;
  21. dfs(to, v);
  22. mx[v] = max(mx[v], sz[to]);
  23. sz[v] += sz[to];
  24. }
  25. G.push_back(v);
  26. }
  27. int cnt[100100];
  28. ll ans = 0;
  29.  
  30. void solve(int v){
  31. G.clear();
  32. dfs(v, 0);
  33. int C = -1;
  34. for(int to: G){
  35. if(C == -1) C = to;
  36. else if(max(mx[C], (int) G.size() - sz[C]) > max(mx[to], (int) G.size() - sz[to])){
  37. C = to;
  38. }
  39. }
  40. int D = G.size();
  41. cnt[0]++;
  42. lev[C] = 0;
  43. for(int to: g[C]){
  44. if(u[to]) continue;
  45. G.clear();
  46. dfs(to, C);
  47. for(int V: G){
  48. if(lev[V] <= k){
  49. ans += cnt[k-lev[V]];
  50. }
  51. }
  52. for(int V: G){
  53. cnt[lev[V]]++;
  54. }
  55. }
  56. for(int i = 0; i < D; i++) cnt[i] = 0;
  57.  
  58. u[C] = 1;
  59. for(int to: g[C]){
  60. if(u[to]) continue;
  61. solve(to);
  62. }
  63.  
  64. }
  65.  
  66. int main(){
  67. scanf("%d%d", &n, &k);
  68. for(int i = 1, x, y;i < n; i++){
  69. scanf("%d%d", &x, &y);
  70. g[x].push_back(y);
  71. g[y].push_back(x);
  72. }
  73. solve(1);
  74. cout << ans << "\n";
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement