rt,这份代码。
#include <bits/stdc++.h>
#define For(i,a,b) for(register int i=a;i<=b;++i)
#define Rep(i,a,b) for(register int i=a;i>=b;--i)
#define ll long long
using namespace std;
inline int read() {
char c = getchar();
int x = 0;
bool f = 0;
for (; !isdigit(c); c = getchar())
f ^= !(c ^ 45);
for (; isdigit(c); c = getchar())
x = x * 10 + (c ^ 48);
if (f)
x = -x;
return x;
}
#define fi first
#define se second
#define pb push_back
#define mkp make_pair
typedef pair<int, int>pii;
typedef vector<int>vi;
#define maxn 500005
#define inf 0x3f3f3f3f
int n, m, res;
ll val[maxn];
bool cmp(int x, int y) {
return val[x] > val[y] || (val[x] == val[y] && x < y);
}
namespace T {
int ch[maxn][2], fa[maxn], typ[maxn];
void rot(int x) {
int y = fa[x], w = fa[x] && ch[fa[x]][1] == x;
if (fa[y])
ch[fa[y]][fa[y] && ch[fa[y]][1] == y] = x;
if (x)
fa[x] = fa[y];
if (y)
ch[y][w] = ch[x][!w];
if (ch[x][!w])
fa[ch[x][!w]] = y;
if (x)
ch[x][!w] = y;
if (y)
fa[y] = x;
typ[x] = typ[y], typ[y] = 0;
}
void splay(int x) {
while (fa[x]) {
int y = fa[x];
if (fa[y])
rot((fa[y] && ch[fa[y]][1] == y) ^ (fa[y] && ch[fa[y]][1] == y) ? x : y);
rot(x);
}
}
void cut(int x) {
splay(x);
if (ch[x][1]) {
fa[ch[x][1]] = 0, typ[ch[x][1]] = typ[x];
ch[x][1] = 0;
}
}
void link(int f, int x) {
bool w = x > f;
splay(x), cut(f);
if (!ch[f][0] && !ch[f][1])
typ[f] = w;
if (typ[f] == w && (typ[x] == w || (!ch[x][0] && !ch[x][1])))
ch[f][1] = x, fa[x] = f;
}
int find(int x) {
int u = ch[x][0], res = -1;
while (1) {
if (cmp(x, u)) {
res = u;
if (!ch[u][0])
return splay(u), res;
u = ch[u][0];
} else {
if (!ch[u][1])
return splay(u), res;
u = ch[u][1];
}
}
}
}
int ch[maxn][2], fa[maxn], f[maxn][5], rt;
void up(int p) {
if (!p)
return;
res -= f[p][4];
int l = ch[p][0], r = ch[p][1], t;
bool ok = 1;
t = f[l][1] + f[r][1];
if (t != f[p][2])
f[p][2] = t, ok = 0;
t = f[l][2] + f[r][2] + f[l][1] * f[r][1];
if (t != f[p][3])
f[p][3] = t, ok = 0;
t = f[l][3] + f[l][2] * f[r][1] + f[l][1] * f[r][2] + f[r][3];
f[p][4] = t, res += t;
if (!ok)
up(fa[p]);
}
void link(int f, int x) {
if (!x)
return;
bool w = x > f;
ch[f][w] = x, fa[x] = f, up(f);
T::link(f, x);
}
void cut(int f, int x) {
if (!x)
return;
bool w = x > f;
ch[f][w] = fa[x] = 0, up(f);
T::cut(f);
}
int son[2];
void mdf(int x, int v) {
val[x] += v;
son[0] = ch[x][0], son[1] = ch[x][1];
cut(x, son[0]), cut(x, son[1]);
while (fa[x] && cmp(x, fa[x])) {
T::splay(x);
int y = fa[x], w = x > y, o, z;
// z:上旋到的点
if (T::ch[x][0])
z = T::find(x);
else
z = y;
cut(y, x), link(y, son[!w]), son[!w] = z;
if (fa[z])
cut(o = fa[z], z), link(o, x);
}
link(x, son[0]), link(x, son[1]);
if (!fa[x])
rt = x;
}
signed main() {
n = read();
For(i, 1, n)f[i][1] = 1;
rt = 1;
For(i, 1, n - 1)link(i, i + 1);
For(i, 1, n)mdf(i, read());
m = read();
For(_, 1, m) {
int x = read(), y = read();
mdf(x, y), printf("%lld\n", res - f[rt][4]);
}
}