dllbridge

Untitled

Nov 8th, 2022
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. /**
  2.  *    author:  tourist
  3.  *    created: 06.11.2022 20:54:05      
  4. **/
  5. #include <bits/stdc++.h>
  6.  
  7. using namespace std;
  8.  
  9. #ifdef LOCAL
  10. #include "algo/debug.h"
  11. #else
  12. #define debug(...) 42
  13. #endif
  14.  
  15. template <typename T>
  16. class fenwick {
  17.  public:
  18.   vector<T> fenw;
  19.   int n;
  20.  
  21.   fenwick(int _n) : n(_n) {
  22.     fenw.resize(n);
  23.   }
  24.  
  25.   void modify(int x, T v) {
  26.     while (x < n) {
  27.       fenw[x] += v;
  28.       x |= (x + 1);
  29.     }
  30.   }
  31.  
  32.   T get(int x) {
  33.     T v{};
  34.     while (x >= 0) {
  35.       v += fenw[x];
  36.       x = (x & (x + 1)) - 1;
  37.     }
  38.     return v;
  39.   }
  40. };
  41.  
  42. int main() {
  43.   ios::sync_with_stdio(false);
  44.   cin.tie(0);
  45.   int tt;
  46.   cin >> tt;
  47.   while (tt--) {
  48.     int n;
  49.     cin >> n;
  50.     string s;
  51.     cin >> s;
  52.     vector<int> a(n + 1);
  53.     for (int i = 0; i < n; i++) {
  54.       a[i + 1] = a[i] + (s[i] == '(' ? 1 : -1);
  55.     }
  56.     int mn = *min_element(a.begin(), a.end());
  57.     for (int i = 0; i <= n; i++) {
  58.       a[i] -= mn;
  59.       assert(0 <= a[i] && a[i] <= n);
  60.     }
  61.     long long ans = 0;
  62.     fenwick<long long> f0(n + 1);
  63.     fenwick<long long> f1(n + 1);
  64.     for (int i = 0; i <= n; i++) {
  65.       ans += f0.get(a[i]) * a[i] - f1.get(a[i]);
  66.       f0.modify(a[i], +1);
  67.       f1.modify(a[i], +a[i]);
  68.     }
  69.     vector<long long> pref(n + 2);
  70.     for (int i = 0; i <= n; i++) {
  71.       pref[i + 1] = pref[i] + a[i];
  72.     }
  73.     vector<int> pr(n + 1);
  74.     vector<int> ne(n + 1);
  75.     for (int i = 0; i <= n; i++) {
  76.       pr[i] = i - 1;
  77.       ne[i] = i + 1;
  78.     }
  79.     vector<vector<int>> at(n + 1);
  80.     for (int i = 0; i <= n; i++) {
  81.       at[a[i]].push_back(i);
  82.     }
  83.     for (int val = n; val >= 0; val--) {
  84.       for (int i : at[val]) {
  85.         int L = pr[i] + 1;
  86.         int R = ne[i];
  87.         long long cur = (pref[i] - pref[L]) - (long long) a[i] * (i - L);
  88.         cur *= R - i;
  89.         ans += cur;
  90.         if (pr[i] != -1) {
  91.           ne[pr[i]] = ne[i];
  92.         }
  93.         if (ne[i] != n + 1) {
  94.           pr[ne[i]] = pr[i];
  95.         }
  96.       }
  97.     }
  98.     cout << ans << '\n';
  99.   }
  100.   return 0;
  101. }
Add Comment
Please, Sign In to add comment