pkse

mootube

Nov 17th, 2025
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct DSU {
  5.     vector<int> a;
  6.     vector<int> b;
  7.     int n;
  8.     DSU (int N) {
  9.         n = N;
  10.         a.resize(n);
  11.         b.resize(n);
  12.         for(int i = 0; i < n; i ++) {
  13.             a[i] = i;
  14.             b[i] = 1;
  15.         }
  16.     }
  17.  
  18.     int leader(int x) {
  19.         if(a[x] == x)
  20.             return x;
  21.         return a[x] = leader(a[x]);
  22.     }
  23.  
  24.     void merge(int x, int y) {
  25.         x = leader(x);
  26.         y = leader(y);
  27.         if(b[x] < b[y])
  28.             swap(x, y);
  29.         b[x] += b[y];
  30.         a[y] = x;
  31.     }
  32.  
  33.     int size(int x) {
  34.         return b[leader(x)];
  35.     }
  36. };
  37.  
  38. struct lol {
  39.     int x, y, c;
  40. };
  41.  
  42. bool cmp1(lol a, lol b) {
  43.     return a.c > b.c;
  44. }
  45.  
  46. bool cmp2(lol a, lol b) {
  47.     return a.x > b.x;
  48. }
  49.  
  50. bool cmp3(lol a, lol b) {
  51.     return a.c < b.c;
  52. }
  53.  
  54. int main() {
  55.     freopen("mootube.in", "r", stdin);
  56.     freopen("mootube.out", "w", stdout);
  57.     ios_base::sync_with_stdio(false);
  58.     cin.tie(nullptr);
  59.    
  60.     int n, q; cin >> n >> q;
  61.  
  62.     DSU dsu(n);
  63.  
  64.     vector<lol> a(n);
  65.     for(int i = 0; i < n - 1; i ++) {
  66.         cin >> a[i].x >> a[i].y >> a[i].c;
  67.         a[i].x --; a[i].y --;
  68.     }
  69.    
  70.     vector<lol> b(q);
  71.     for(int i = 0; i < q; i ++) {
  72.         cin >> b[i].x >> b[i].y; b[i].y --;
  73.         b[i].c = i;
  74.     }
  75.  
  76.     sort(a.begin(), a.end(), cmp1);
  77.     sort(b.begin(), b.end(), cmp2);
  78.  
  79.     for(int i = 0, j = 0; i < q; i ++) {
  80.         while(j < n && a[j].c >= b[i].x) {
  81.             dsu.merge(a[j].x, a[j].y);
  82.             j ++;
  83.         }
  84.         b[i].x = dsu.size(b[i].y) - 1;
  85.     }
  86.  
  87.     sort(b.begin(), b.end(), cmp3);
  88.     for(int i = 0; i < q; i ++) {
  89.         cout << b[i].x << '\n';
  90.     }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment