Beingamanforever

Distance Trees, Cses, Dp on Trees, O(N*K)

Jan 15th, 2025
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long
  4. #define all(x) (x).begin(), (x).end()
  5. typedef vector<int> vi;
  6. typedef vector<vi> vvi;
  7. typedef vector<pair<int, int>> vpi;
  8. typedef pair<int, int> pi;
  9. #define f first
  10. #define s second
  11. #define pb push_back
  12. #define endl "\n"
  13. #define yes cout << "YES" << endl
  14. #define no cout << "NO" << endl
  15. const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 5e4 + 15, L = 19, K = 515;
  16. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  17. // -----------------------------------------------------------------------------
  18. vi adj[N];
  19. int dp1[N][K], dp2[N][K], n, k;
  20. void dfs1(int u, int p)
  21. {
  22.     dp2[u][0] = 1;
  23.     for (auto &v : adj[u])
  24.     {
  25.         if (v == p)
  26.         {
  27.             continue;
  28.         }
  29.         dfs1(v, u);
  30.         for (int x = 1; x < K; x++)
  31.         {
  32.             dp2[u][x] += dp2[v][x - 1];
  33.         }
  34.     }
  35. }
  36. void dfs2(int u, int p)
  37. {
  38.     if (u == 1)
  39.     {
  40.         // root, dp1[u][x] = dp2[u][x]
  41.         for (int x = 0; x < K; x++)
  42.         {
  43.             dp1[u][x] = dp2[u][x];
  44.         }
  45.     }
  46.     else
  47.     {
  48.         for (int x = 0; x < K; x++)
  49.         {
  50.             dp1[u][x] = dp2[u][x] + ((x > 0 ? dp1[p][x - 1] : 0) - (x > 1 ? dp2[u][x - 2] : 0));
  51.         }
  52.     }
  53.     for (auto &v : adj[u])
  54.     {
  55.         if (v == p)
  56.         {
  57.             continue;
  58.         }
  59.         dfs2(v, u);
  60.     }
  61. }
  62. void solve()
  63. {
  64.     // dp1(u,x) number nodes at distance of x from u
  65.     // dp2(u,x) number of nodes at distance x from u, in it's subtree
  66.     cin >> n >> k;
  67.     for (int i = 1; i <= (n - 1); i++)
  68.     {
  69.         int u, v;
  70.         cin >> u >> v;
  71.         adj[u].pb(v);
  72.         adj[v].pb(u);
  73.     }
  74.     dfs1(1, -1);
  75.     dfs2(1, -1);
  76.     int ans = 0;
  77.     for (int i = 1; i <= n; i++)
  78.     {
  79.         ans += dp1[i][k];
  80.     }
  81.     cout << (ans / 2) << endl;
  82.     return;
  83. }
  84.  
  85. signed main()
  86. {
  87.     // __START__;
  88.     ios_base::sync_with_stdio(false);
  89.     cin.tie(NULL);
  90.     cout.tie(NULL);
  91.     int t = 1;
  92.     // cin >> t;
  93.     while (t--)
  94.     {
  95.         solve();
  96.     }
  97.     // __END__;
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment