1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
|
#include <algorithm> #include <cmath> #include <cstdio> #include <ctime> #include <cstring> #include <iostream> #include <queue> #include <map> #include <set> #include <string> #include <list> #include <forward_list> #include <stack> #include <unordered_set> #include <vector> #include <limits.h>
using namespace std; const long long MAX = 1e6 + 7;
char arr[MAX * 2];
struct Node { int left, right; int val, min, max, lazy; };
Node tree[MAX * 8];
void build(int left, int right, int treeIndex = 1) { auto &node = tree[treeIndex]; node.left = left; node.right = right; if (left != right) { int mid = (left + right) / 2; build(left, mid, treeIndex * 2); build(mid + 1, right, treeIndex * 2 + 1); } }
void update(int left, int right, int val, int treeIndex = 1) { auto &node = tree[treeIndex]; if (node.left == node.right) { node.val += val; node.max = node.val; node.min = node.val; return; } if (node.left >= left && node.right <= right) { node.lazy += val; node.max += val; node.min += val; return; } int mid = (node.left + node.right) / 2; if (mid >= left) { update(left, right, val, treeIndex * 2); } if (mid < right) { update(left, right, val, treeIndex * 2 + 1); } node.max = max(tree[treeIndex * 2].max, tree[treeIndex * 2 + 1].max) + node.lazy; node.min = min(tree[treeIndex * 2].min, tree[treeIndex * 2 + 1].min) + node.lazy; }
int query(int pos, int treeIndex = 1) { auto &node = tree[treeIndex]; if (node.left == node.right) { return node.val; } int mid = (node.left + node.right) / 2; if (pos <= mid) { return node.lazy + query(pos, treeIndex * 2); } else { return node.lazy + query(pos, treeIndex * 2 + 1); } }
int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); int n; int arrCursor = MAX; cin >> n; char c; const int rMax = arrCursor + n + 5; const int lMin = arrCursor - n + 5; build(lMin, rMax); while (n--) { cin >> c; if (c == 'L') { arrCursor -= 1; } else if (c == 'R') { arrCursor += 1; } else { char origin = arr[arrCursor]; arr[arrCursor] = c; if (c == '(') { if (origin == ')') { update(arrCursor, rMax, 2); } else if (origin != '(') { update(arrCursor, rMax, 1); } } else if (c == ')') { if (origin == '(') { update(arrCursor, rMax, -2); } else if (origin != ')') { update(arrCursor, rMax, -1); } } else { if (origin == '(') { update(arrCursor, rMax, -1); } else if (origin == ')') { update(arrCursor, rMax, 1); } } } if (tree[1].min >= 0 && query(rMax) == 0) { cout << tree[1].max << " "; } else { cout << -1 << " "; } } return 0; }
|