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
| #include <iostream> #include <stack> #include <cstring> #include <cstdio> using namespace std; typedef long long ll; #define wfor(i,j,k) for(i=j;i<k;++i) #define mfor(i,j,k) for(i=j;i>=k;--i)
const int maxn = 50005; int tree[maxn << 2]; void push_up(int id) { tree[id] = tree[id << 1] + tree[id << 1 | 1]; } void updata(int l, int r, int id, int pos, int number) { if (l == r) { tree[id] = number; return ; } int mid = (l + r) >> 1; if (mid >= pos) updata(l, mid, id << 1, pos, number); else updata(mid + 1, r, id << 1 | 1, pos, number); push_up(id); } int flag = 0; void query(int l, int r, int id, int pos, int &x, int &y) { if (flag) return; if (tree[id] == 0) { return ; } if (l == r) { if (tree[id] == 1) { if (l == pos) { flag = 1; return ; } if (l <= pos) x = max(x, l); else y = min(y, l); } return ; } int mid = (l + r) >> 1; if (mid >= x) query(l, mid, id << 1, pos, x, y); if (mid < y) query(mid + 1, r, id << 1 | 1, pos, x, y); } int des[maxn]; int main() { std::ios::sync_with_stdio(false); int n, m; while (cin >> n >> m) { int i; stack<int>last; memset(tree, 0, sizeof(tree)); memset(des, 0, sizeof(des)); wfor(i, 0, m) { char c; cin >> c; if (c == 'D') { int pos; cin >> pos; last.push(pos); des[pos] = 1; updata(1, n, 1, pos, 1); } else if (c == 'Q') { int pos; cin >> pos; int x = -1, y = 1e9; flag = 0; query(1, n, 1, pos, x, y); if (flag) { cout << 0 << endl; } else { int ans = 0; if (x == -1 && y == 1e9) { ans = n; } else if (x == -1) { ans = pos; ans += y - pos - 1; } else if (y == 1e9) { ans = pos - x; ans += n - pos; } else { ans += pos - x; ans += y - pos - 1; } cout << ans << endl; } } else { while (des[last.top()] == 0) { last.pop(); } updata(1, n, 1, last.top(), 0); des[last.top()] = 0; last.pop(); } } } return 0; }
|