【ZJOI2012】小蓝的好友 - 题解

题目链接

【ZJOI2012】小蓝的好友

做法

至少包含一个点的矩阵数等于总矩阵数减去不包含任意一个点的矩阵数。
考虑将点按照纵坐标排序,进行类似扫描线的操作。每一列有用的点是最靠近当前行的点,记录它们的纵坐标。如果这一层存在一段长度为 $ s $ 不包含点,则它对答案的贡献为 $ \frac{(s + 1) \times s}{2} $ ;如果是纵坐标上一段都满足,那就再乘上纵坐标上的长度。
维护一个 $ Treap $ ,$ value $ 值中序遍历表示横坐标的一段,$ key $ 值表示横坐标为该值时纵坐标的最大值。每次一些节点 $ key $ 值会变大,然后用 $ splay $ 的方式旋转满足 $ Treap $ 的性质,同时维护答案。
由于数据随机,所以复杂度 $ O(n \log n) $ 。

#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;
}
posted @ 2019-04-21 18:30  daniel14311531  阅读(219)  评论(0编辑  收藏  举报