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
| #include <iostream> #include <algorithm> using namespace std; using LL = long long; const int N = 500001; int n, a[N], b[N]; LL ans; struct Node { int l, r, v; } tr[N << 2]; void pushup(int u) { tr[u].v = tr[u << 1].v + tr[u << 1 | 1].v; } void build(int u, int l, int r) { tr[u] = {l, r, 0}; if (l == r) return; int mid = l + r >> 1; build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r); } void update(int u, int pos) { if (tr[u].l == tr[u].r) ++tr[u].v; else { int mid = tr[u].l + tr[u].r >> 1; if (pos <= mid) update(u << 1, pos); else update(u << 1 | 1, pos); pushup(u); } } int query(int u, int l, int r) { if (l <= tr[u].l && tr[u].r <= r) return tr[u].v; int mid = tr[u].l + tr[u].r >> 1; int ret = 0; if (l <= mid) ret = query(u << 1, l, r); if (r > mid) ret += query(u << 1 | 1, l, r); return ret; } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i], b[i] = a[i]; build(1, 1, n); sort(b + 1, b + n + 1); int len = unique(b + 1, b + n + 1) - b - 1; for (int i = 1; i <= n; ++i) { int pos = lower_bound(b + 1, b + len + 1, a[i]) - b; if (pos != n) ans += query(1, pos + 1, n); update(1, pos); } cout << ans << endl; return 0; }
|