Advertisement
Josif_tepe

Untitled

May 10th, 2023
778
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <stack>
  4. //#include <bits/stdc++.h>
  5. using namespace std;
  6. const int maxn = 1e6 + 10;
  7. vector<int> segment_tree[3 * maxn];
  8. int next_idx[maxn];
  9. void build(int L, int R, int position) {
  10.     if(L == R) {
  11.         segment_tree[position].push_back(next_idx[L]);
  12.     }
  13.     else {
  14.         int middle = (L + R) / 2;
  15.         build(L, middle, 2 * position);
  16.         build(middle + 1, R, 2 * position + 1);
  17.         merge(segment_tree[2 * position].begin(), segment_tree[2 * position].end(), segment_tree[2 * position + 1].begin(), segment_tree[2 * position + 1].end(), back_inserter(segment_tree[position]));
  18.     }
  19. }
  20. int query(int L, int R, int position, int i, int j, int x) {
  21.     // L  R i L R j L R
  22.     if(i <= L and R <= j) {
  23.         return lower_bound(segment_tree[position].begin(), segment_tree[position].end(), x) - segment_tree[position].begin();
  24.     }
  25.     if(R < i or j < L) {
  26.         return 0;
  27.     }
  28.     int middle = (L + R) / 2;
  29.     return query(L, middle, 2 * position, i, j, x) + query(middle + 1, R, 2 * position + 1, i, j, x);
  30. }
  31. int main() {
  32.     ios_base::sync_with_stdio(false);
  33.     string s;
  34.     cin >> s;
  35.     stack<int> st;
  36.     for(int i = 0; i < s.size(); i++) {
  37.         next_idx[i] = (int) s.size();
  38.     }
  39.     for(int i = 0; i < s.size(); i++) {
  40.         if(s[i] == '(') {
  41.             st.push(i);
  42.         }
  43.         else {
  44.             if(!st.empty()) {
  45.                 next_idx[st.top()] = i;
  46.                 st.pop();
  47.             }
  48.         }
  49.     }
  50.     int q;
  51.     cin >> q;
  52.     build(0, s.size(), 1);
  53.     for(int i = 0; i < q; i++) {
  54.         int a, b;
  55.         cin >> a >> b;
  56.         a--;
  57.         b--;
  58.         cout << query(0, s.size(), 1, a, b, b + 1) * 2 << "\n";
  59.        
  60.     }
  61.     return 0;
  62. }
  63. /*
  64.  ())(())(())(
  65.  1NN65NN109NNN
  66.  
  67.  
  68.  */
  69.  
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement