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
| #include <cstdio> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type, class ...rest> void read (Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } typedef long long LL; typedef tree <int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> Tree; const int N = 2e5 + 10; LL ans; int n, m, w[N]; struct Node { int l, r; Tree t; } tr[N << 2]; void build (int l = 1, int r = n, int x = 1) { tr[x].l = l, tr[x].r = r; for (int i = l; i <= r; ++i) tr[x].t.insert(w[i]); if (l == r) return; int mid = l + r >> 1; build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1); } void add (int t, int x = 1) { tr[x].t.insert(w[t]); if (tr[x].l == tr[x].r) return; int mid = tr[x].l + tr[x].r >> 1; add(t, x << 1 | (t > mid)); } void del (int t, int x = 1) { tr[x].t.erase(w[t]); if (tr[x].l == tr[x].r) return; int mid = tr[x].l + tr[x].r >> 1; del(t, x << 1 | (t > mid)); } int QueryLess (int l, int r, int k, int x = 1) { if (l > r || tr[x].l > r || l > tr[x].r) return 0; if (tr[x].l >= l && tr[x].r <= r) return tr[x].t.order_of_key(k); return QueryLess(l, r, k, x << 1) + QueryLess(l, r, k, x << 1 | 1); } int QueryGreater (int l, int r, int k, int x = 1) { if (l > r || tr[x].l > r || l > tr[x].r) return 0; if (tr[x].l >= l && tr[x].r <= r) return tr[x].t.size() - tr[x].t.order_of_key(k + 1); return QueryGreater(l, r, k, x << 1) + QueryGreater(l, r, k, x << 1 | 1); } int main () { read(n, m); for (int i = 1; i <= n; ++i) w[i] = i; build(); for (int a, b; m; --m) { read(a, b); if (a > b) swap(a, b); ans -= QueryLess(a + 1, b - 1, w[a]) + QueryGreater(a + 1, b - 1, w[b]) + (w[a] > w[b]); ans += QueryLess(a + 1, b - 1, w[b]) + QueryGreater(a + 1, b - 1, w[a]) + (w[b] > w[a]); del(a), del(b), swap(w[a], w[b]), add(a), add(b); write(ans), puts(""); } return 0; }
|