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
| #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, q;
int a[N];
struct Segmentree { int sum; int lmx, rmx; int lmn, rmn; int val1, val2, val; #define ls(p) (p << 1) #define rs(p) (p << 1 | 1) }t[N << 2];
void push_up(int p) { t[p].sum = t[ls(p)].sum + t[rs(p)].sum; t[p].lmx = max(t[ls(p)].lmx, t[ls(p)].sum + t[rs(p)].lmx); t[p].rmx = max(t[rs(p)].rmx, t[rs(p)].sum + t[ls(p)].rmx); t[p].lmn = min(t[ls(p)].lmn, t[ls(p)].sum + t[rs(p)].lmn); t[p].rmn = min(t[rs(p)].rmn, t[rs(p)].sum + t[ls(p)].rmn); t[p].val1 = max({t[ls(p)].val1, t[rs(p)].val1 - t[ls(p)].sum, t[rs(p)].lmx + t[ls(p)].rmx * 2 - t[ls(p)].sum}); t[p].val2 = max({t[rs(p)].val2, t[ls(p)].val2 + t[rs(p)].sum, t[rs(p)].sum - t[rs(p)].lmn * 2 - t[ls(p)].rmn}); t[p].val = max({t[ls(p)].val, t[rs(p)].val, t[ls(p)].val2 + t[rs(p)].lmx, t[rs(p)].val1 - t[ls(p)].rmn}); }
void build(int l, int r, int p) { if(l == r) { t[p].sum = a[l]; t[p].lmx = t[p].rmx = max(a[l], 0); t[p].lmn = t[p].rmn = min(a[l], 0); t[p].val1 = t[p].val2 = t[p].val = 1; return; } int mid = (l + r) >> 1; build(l, mid, ls(p)); build(mid + 1, r, rs(p)); push_up(p); }
void change(int l, int r, int p, int x, int k) { if(l == r) { t[p].sum = k; t[p].lmx = t[p].rmx = max(k, 0); t[p].lmn = t[p].rmn = min(k, 0); return; } int mid = (l + r) >> 1; if(x <= mid) change(l, mid, ls(p), x, k); else change(mid + 1, r, rs(p), x, k); push_up(p); }
int main() { scanf("%d%d", &n, &q); n = (n - 1) << 1; for(int i = 1; i <= n; i++) { char x;cin >> x; if(x == '(')a[i] = 1; if(x == ')')a[i] = -1; } build(1, n, 1); printf("%d\n", t[1].val); for(int i = 1; i <= q; i++) { int x, y; scanf("%d%d", &x, &y); swap(a[x], a[y]); change(1, n, 1, x, a[x]); change(1, n, 1, y, a[y]); printf("%d\n", t[1].val); } return 0; }
|