1
+ // http://codeforces.com/contest/380/problem/C
2
+
3
+ #include < bits/stdc++.h>
4
+ #define __ ios_base::sync_with_stdio (0 ); cin.tie(0 );
5
+
6
+ using namespace std ;
7
+
8
+ const int N = 1001000 ;
9
+
10
+ vector<int > L (4 * N, 0 ), R(4 * N, 0 ), ans(4 * N, 0 );
11
+ string s;
12
+
13
+ struct node {
14
+ int x,y,c;
15
+
16
+ node () {};
17
+ node (int _x, int _y, int _c) : x(_x), y(_y), c(_c) {};
18
+ };
19
+
20
+ node segmentTree (int x, int y, int id, int l, int r) {
21
+ if (l >= y || x >= r) return node (0 , 0 , 0 );
22
+ if (x <= l && r <= y)
23
+ return node (L[id], R[id], ans[id]);
24
+
25
+ int mid = (l + r) / 2 ;
26
+ node a = segmentTree (x, y, 2 * id, l, mid);
27
+ node b = segmentTree (x, y, 2 * id + 1 , mid, r);
28
+
29
+ int res, tmp, left, right;
30
+ tmp = min (a.x , b.y );
31
+ res = a.c + b.c + tmp;
32
+ left = a.x + b.x - tmp;
33
+ right = a.y + b.y - tmp;
34
+ return node (left, right, res);
35
+ }
36
+
37
+ void init (int id, int l, int r) {
38
+ if (r - l < 2 ) {
39
+ if (s[l] == ' (' )
40
+ L[id] = 1 ;
41
+ else
42
+ R[id] = 1 ;
43
+
44
+ return ;
45
+ }
46
+
47
+ int mid = (r + l) / 2 ;
48
+ init (2 * id, l, mid);
49
+ init (2 * id + 1 , mid, r);
50
+
51
+ int tmp = min (L[2 * id], R[2 * id + 1 ]);
52
+ ans[id] = ans[2 * id] + ans[2 * id + 1 ] + tmp;
53
+ L[id] = L[2 * id] + L[2 * id + 1 ] - tmp;
54
+ R[id] = R[2 * id] + R[2 * id + 1 ] - tmp;
55
+ }
56
+
57
+ int main () { __
58
+ cin >> s;
59
+
60
+ int n = s.size ();
61
+ init (1 , 0 , n);
62
+
63
+ int q;
64
+ cin >> q;
65
+ for (int i = 0 ; i < q; ++i) {
66
+ int l, r;
67
+ cin >> l >> r;
68
+ node res = segmentTree (l - 1 , r, 1 , 0 , n);
69
+ cout << 2 * res.c << endl;
70
+ }
71
+
72
+ return 0 ;
73
+ }
0 commit comments