Bzoj2141: 排队
题面
Sol
树状数组套线段树模板题
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
const int _(2e4 + 1);
typedef long long ll;
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int h[_], n, num, rt[_], o[_], len;
struct Segment{
int ls, rs, sz;
} T[_ * 200];
ll ans;
IL void Modify(RG int &x, RG int l, RG int r, RG int p, RG int v){
if(!x) x = ++num; T[x].sz += v;
if(l == r) return;
RG int mid = (l + r) >> 1;
if(p <= mid) Modify(T[x].ls, l, mid, p, v);
else Modify(T[x].rs, mid + 1, r, p, v);
}
IL void Add(RG int x, RG int v, RG int d){
for(; x <= n; x += x & -x) Modify(rt[x], 1, len, v, d);
}
IL int QuerySum(RG int x, RG int l, RG int r, RG int ql, RG int qr){
if(!x) return 0;
if(ql <= l && qr >= r) return T[x].sz;
RG int mid = (l + r) >> 1, ret = 0;
if(ql <= mid) ret = QuerySum(T[x].ls, l, mid, ql, qr);
if(qr > mid) ret += QuerySum(T[x].rs, mid + 1, r, ql, qr);
return ret;
}
IL int Sum(RG int x, RG int l, RG int r){
RG int ret = 0;
if(l > r) return 0;
for(; x; x -= x & -x) ret += QuerySum(rt[x], 1, len, l, r);
return ret;
}
int main(RG int argc, RG char* argv[]){
n = Input();
for(RG int i = 1; i <= n; ++i) o[++len] = h[i] = Input();
sort(o + 1, o + len + 1), len = unique(o + 1, o + len + 1) - o - 1;
for(RG int i = 1; i <= n; ++i){
h[i] = lower_bound(o + 1, o + len + 1, h[i]) - o;
ans += Sum(i, h[i] + 1, len), Add(i, h[i], 1);
}
printf("%lld\n", ans);
for(RG int m = Input(); m; --m){
RG int x = Input(), y = Input();
if(x > y) swap(x, y);
Add(x, h[x], -1), Add(y, h[y], -1);
ans -= Sum(x, h[x] + 1, len) + Sum(y, h[y] + 1, len);
ans -= Sum(n, 1, h[x] - 1) - Sum(x - 1, 1, h[x] - 1);
ans -= Sum(n, 1, h[y] - 1) - Sum(y - 1, 1, h[y] - 1);
if(h[x] > h[y]) --ans;
swap(h[x], h[y]);
if(h[x] > h[y]) ++ans;
ans += Sum(x, h[x] + 1, len) + Sum(y, h[y] + 1, len);
ans += Sum(n, 1, h[x] - 1) - Sum(x - 1, 1, h[x] - 1);
ans += Sum(n, 1, h[y] - 1) - Sum(y - 1, 1, h[y] - 1);
Add(x, h[x], 1), Add(y, h[y], 1);
printf("%lld\n", ans);
}
return 0;
}