fork download
  1. #include <cstdio>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. int const N = 2e5 + 10;
  6.  
  7. vector <int> e[N];
  8. bool has_p[N];
  9. int n, k;
  10. long long tot;
  11.  
  12. struct FenwickTree {
  13. int x[N], n;
  14. int static const OFFSET = 5;
  15.  
  16. FenwickTree(int n=N):n(n) {}
  17.  
  18. void add(int p, int o) {
  19. for (p+=OFFSET; p<n; p+=p&-p) x[p] += o;
  20. }
  21. int sum(int p) {
  22. int ret = 0;
  23. for (p+=OFFSET; p>0; p-=p&-p) ret += x[p];
  24. return ret;
  25. }
  26. } T;
  27.  
  28. void dfs(int x) {
  29. tot += T.sum(x+k) - T.sum(x-k-1);
  30. T.add(x, 1);
  31. for (int i=(int)e[x].size()-1; i>=0; --i) dfs(e[x][i]);
  32. T.add(x, -1);
  33. }
  34.  
  35. int main() {
  36. scanf("%d%d", &n, &k);
  37. for (int i=1,p,c; i<n; ++i) {
  38. scanf("%d%d", &p, &c);
  39. e[p].push_back(c);
  40. has_p[c] = true;
  41. }
  42. int root = -1;
  43. for (root=1; root<=n&&has_p[root]; ++root);
  44. dfs(root);
  45. printf("%lld\n", tot);
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 6780KB
stdin
Standard input is empty
stdout
0