Advertisement
fooker

Path Queries

Jan 4th, 2024
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4.  
  5. const ll nmax = 1e9+7;
  6. const ll nmax2 = 998244353;
  7.  
  8. class DSU {
  9. public:
  10.     std::vector<ll> f, siz;
  11.     DSU(ll n) : f(n + 1), siz(n + 1, 1) {
  12.         std::iota(f.begin() + 1, f.end(), 1);
  13.     }
  14.     ll leader(ll x) {
  15.         while (x != f[x]) x = f[x] = f[f[x]];
  16.         return x;
  17.     }
  18.     bool same(ll x, ll y) {
  19.         return leader(x) == leader(y);
  20.     }
  21.     void merge(ll x, ll y) {
  22.         x = leader(x);
  23.         y = leader(y);
  24.         if (x == y) return;
  25.         siz[x] += siz[y];
  26.         f[y] = x;
  27.     }
  28.     ll size(ll x) {
  29.         return siz[leader(x)];
  30.     }
  31. };
  32.  
  33. int main(){
  34.     std::ios_base::sync_with_stdio(false);
  35.     std::cin.tie(0);
  36.     std::cout.tie(0);
  37.  
  38.     ll n, m;
  39.     std::cin >> n >> m;
  40.  
  41.     std::map<ll, std::vector<std::pair<ll, ll>>> mp;
  42.     std::vector<ll> adj[n + 1];
  43.     std::set<std::pair<ll, ll>> l;
  44.     for (ll i = 1, x, y, z; i < n; i++){
  45.         std::cin >> x >> y >> z;
  46.         adj[x].push_back(y);
  47.         adj[y].push_back(x);
  48.         mp[z].push_back({x, y});
  49.         l.insert({z, 0});
  50.     }
  51.  
  52.     std::map<ll, ll> ans;
  53.     ll q[m + 1];
  54.     for (ll i = 1; i <= m; i++){
  55.         std::cin >> q[i];
  56.         l.insert({q[i], 1});
  57.  
  58.     }
  59.  
  60.     std::sort(l.begin(), l.end());
  61.     DSU dsu(n);
  62.  
  63.     ll res = 0;
  64.     for (auto i : l){
  65.         if (i.second == 1){
  66.             ans[i.first] = res;
  67.         } else {
  68.             for (auto j : mp[i.first]){
  69.                 ll A = j.first;
  70.                 ll B = j.second;
  71.                 ll siz_A = dsu.siz[A];
  72.                 ll siz_B = dsu.siz[B];
  73.                 res = res - (siz_A * (siz_A - 1)) / 2 - (siz_B * (siz_B - 1)) / 2 + ((siz_A + siz_B) * (siz_A + siz_B - 1)) / 2;
  74.                 dsu.merge(A, B);
  75.             }  
  76.         }
  77.     }
  78.  
  79.     for (ll i = 1; i <= m; i++){
  80.         std::cout << ans[q[i]] << ' ';
  81.     }
  82.  
  83.  
  84. }
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement