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
| #include <bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; const int N = 400010; int n, m, q; ll ans = 0, sum = 0; vector<int> e[N]; int ch[2][N], sz[N], dep[N], fa[N], tot, rt; ll val[N]; int sta[N], top;
void update(int u) { if(!u) return ; sz[u] = 1; if(ch[0][u]) sz[u] += sz[ch[0][u]]; if(ch[1][u]) sz[u] += sz[ch[1][u]]; sum -= val[u]; val[u] = (ll)sz[u] * (sz[u] + 1) / 2 * (dep[fa[u]] - dep[u]); sum += val[u]; } void build(int &u, int ff, int l, int r) { u = (l + r) >> 1, fa[u] = ff; if(l < u) build(ch[0][u], u, l, u - 1); if(u < r) build(ch[1][u], u, u + 1, r); update(u); } void insert(int u) { top = 0, dep[u] = tot; for(; dep[u] > dep[fa[u]];) { int y = fa[u], z = fa[y], k = ch[1][y] == u, w = ch[k ^ 1][u]; ch[ch[1][z] == y][z] = u; ch[k][y] = w, ch[k ^ 1][u] = y; fa[w] = y; fa[u] = z, fa[y] = u; sta[++top] = y; } sta[++top] = u; for(int i = 1; i <= top; i++) { update(sta[i]); if(ch[0][sta[i]]) update(ch[0][sta[i]]); if(ch[1][sta[i]]) update(ch[1][sta[i]]); } } int main() { scanf("%d%d%d", &n, &m, &q), build(ch[1][rt], 0, 1, m); ans = (ll)n * (n + 1) / 2 * m * (m + 1) / 2; for(int i = 1, x, y; i <= q; i++) scanf("%d%d", &x, &y), e[x].pb(y); for(int i = 1; i <= n; i++) { ++tot, ++dep[rt]; if(ch[0][rt]) update(ch[0][rt]); if(ch[1][rt]) update(ch[1][rt]); for(int j = 0; j < e[i].size(); j++) insert(e[i][j]); ans -= sum; } printf("%lld\n", ans); return 0; }
|