BZOJ 3289 Mato的文件管理
莫队算法+树状数组转移
#include<cstdio> #include<cstring> #include<cmath> #include<queue> #include<algorithm> using namespace std; const int maxn = 50000 + 10; int n, m; int tmp[maxn], a[maxn], lsh[maxn], cnt; int pos[maxn]; int c[maxn]; long long ans[maxn], Ans; int L, R; struct X { int l, r, id; }s[maxn]; int f(int x) { int l = 1, r = cnt; while (l <= r) { int mid = (l + r) / 2; if (lsh[mid] < x) l = mid + 1; else if (lsh[mid]>x) r = mid - 1; else return mid; } } void LSH() { sort(tmp + 1, tmp + 1 + n); cnt = 0, lsh[++cnt] = tmp[1]; for (int i = 2; i <= n; i++) { if (tmp[i] == tmp[i - 1]) continue; lsh[++cnt] = tmp[i]; } for (int i = 1; i <= n; i++) a[i] = f(a[i]); } bool cmp(const X&a, const X&b) { if (pos[a.l] == pos[b.l]) return a.r < b.r; return a.l < b.l; } int lowbit(int x) { return x&(-x); } void update(int pos, int val) { while (pos <= cnt) c[pos] = c[pos] + val, pos = pos + lowbit(pos); } int getsum(int pos) { int res = 0; while (pos > 0) res = res + c[pos], pos = pos - lowbit(pos); return res; } int main() { while (~scanf("%d", &n)) { int sz = sqrt(n); for (int i = 1; i <= n; i++) { pos[i] = i / sz; scanf("%d", &tmp[i]); a[i] = tmp[i]; } LSH(); scanf("%d", &m); for (int i = 1; i <= m; i++) { scanf("%d%d", &s[i].l, &s[i].r); s[i].id = i; } sort(s + 1, s + 1 + m, cmp); for (int i = s[1].l; i <= s[1].r; i++) { int sum = getsum(cnt) - getsum(a[i]); Ans = Ans + (long long)sum; update(a[i], 1); } ans[s[1].id] = Ans; L = s[1].l; R = s[1].r; for (int i = 2; i <= m; i++) { while (L < s[i].l) { int sum = getsum(a[L] - 1); Ans = Ans - (long long)sum; update(a[L], -1); L++; } while (L > s[i].l) { L--; int sum = getsum(a[L] - 1); Ans = Ans + (long long)sum; update(a[L], 1); } while (R < s[i].r) { R++; int sum = getsum(cnt) - getsum(a[R]); Ans = Ans + (long long)sum; update(a[R], 1); } while (R > s[i].r) { int sum = getsum(cnt) - getsum(a[R]); Ans = Ans - (long long)sum; update(a[R], -1); R--; } ans[s[i].id] = Ans; } for (int i = 1; i <= m; i++) printf("%lld\n", ans[i]); } return 0; }