ohwhatalovelyday

Untitled

Dec 26th, 2021
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define FASTER() ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  4. #define ff first
  5. #define ss second
  6. #define pb push_back
  7. #define all(a) a.begin(), a.end()
  8. #define dbg(x) cerr<<" "<<#x<<" "<<x<<endl
  9.  
  10. typedef long long ll;
  11.  
  12. using namespace std;
  13.  
  14. int root = -1;
  15.  
  16. void root_find(int v, int p, vector <vector <int>> &gr, vector <int> &cost) {
  17.     if(gr[v].size() == 0 && cost[v] == -1) {
  18.         root = v;
  19.         return;
  20.     }
  21.     for(auto to : gr[v]) {
  22.         if(to != p) {
  23.             root_find(to, v, gr, cost);
  24.         }
  25.     }
  26. }
  27.  
  28. bool swap_needed(pair <int, int> &l, pair <int, int> &r) {
  29.     if(l.ff > r.ss) {
  30.         return true;
  31.     }
  32.     if(l.ff == r.ss) {
  33.         if(l.ff > r.ss) return true;
  34.     }
  35.     return false;
  36. }
  37.  
  38. pair <int, pair <int, int>> get(int v, vector <int> &left, vector <int> &right, vector <int> &cost) {
  39.     if(cost[v] != -1) {
  40.         return {0, {cost[v], cost[v]}};
  41.     }
  42.     auto l = get(left[v], left, right, cost),
  43.         r = get(right[v], left, right, cost);
  44.     int sum = l.ff + r.ff;
  45.     if(swap_needed(l.ss, r.ss)) {
  46.         swap(l.ss, r.ss);
  47.         sum++;
  48.     }
  49.     pair <int, int> tmp = {l.ss.ff, r.ss.ff};
  50.     return {sum, tmp};
  51. }
  52.  
  53. void solve() {
  54.     int n;
  55.     cin >> n;
  56.     vector <int> left(n, -1), right(n, -1);
  57.     vector <int> cost(n, -1);
  58.     vector <vector <int>> revgr(n);
  59.     int leaf = -1;
  60.     for(int i = 0; i < n; i++) {
  61.         int l, r;
  62.         cin >> l >> r;
  63.         if(l == -1) {
  64.             cost[i] = r;
  65.             leaf = i;
  66.         } else {
  67.             l--; r--;
  68.             revgr[l].pb(i);
  69.             revgr[r].pb(i);
  70.             left[i] = l;
  71.             right[i] = r;
  72.         }
  73.     }
  74. //    root_find(leaf, -1, revgr, cost);
  75.     auto ans = get(0, left, right, cost);
  76.     dbg(ans.ss.ff); dbg(ans.ss.ss);
  77.     cout << ans.ff <<  '\n';
  78. }
  79.  
  80. int main() {
  81.     FASTER();
  82.     int t;
  83.     cin >> t;
  84.     while(t--) {
  85.         solve();
  86.     }
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment