bzoj 2738 矩阵乘法 整体二分+树状数组

题面

题目传送门

解法

发现可持久化数据结构并不能维护这个东西

所以考虑整体二分

在求的时候把\([1,mid]\)的所有数的位置+1,然后比较整个矩阵内比\(mid\)大的数是否比\(k\)

时间复杂度:\(O((n^2+q)\ log^2\ n)\)

代码

#include <bits/stdc++.h>
#define M 60010
#define N 510
using namespace std;
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Node {
	int x, y, v;
	bool operator < (const Node &a) const {
		return v < a.v;
	}
} a[N * N];
struct Que {
	int x1, y1, x2, y2, k;
} b[M];
int n, q, len, now, tx[M], ty[M], c[M], ans[M], f[N][N];
int lowbit(int x) {return x & -x;}
void modify(int x, int y, int v) {
	for (int i = x; i <= n; i += lowbit(i))
		for (int j = y; j <= n; j += lowbit(j))
			f[i][j] += v;
}
int query(int x, int y) {
	int ret = 0;
	for (int i = x; i; i -= lowbit(i))
		for (int j = y; j; j -= lowbit(j))
			ret += f[i][j];
	return ret;
}
void solve(int l, int r, int L, int R) {
	if (l > r) return;
	if (L == R) {
		for (int i = l; i <= r; i++)
			ans[c[i]] = a[L].v;
		return;
	}
	int mid = (L + R) >> 1, l1 = 0, l2 = 0;
	for (int i = L; i <= mid; i++) modify(a[i].x, a[i].y, 1);
	for (int i = l; i <= r; i++) {
		int x1 = b[c[i]].x1, y1 = b[c[i]].y1, x2 = b[c[i]].x2, y2 = b[c[i]].y2;
		int sum = query(x2, y2) - query(x1 - 1, y2) - query(x2, y1 - 1) + query(x1 - 1, y1 - 1);
		if (b[c[i]].k <= sum) tx[++l1] = c[i]; else ty[++l2] = c[i], b[c[i]].k -= sum;
	}
	for (int i = l; i < l + l1; i++) c[i] = tx[i - l + 1];
	for (int i = l + l1; i <= r; i++) c[i] = ty[i - l - l1 + 1];
	for (int i = L; i <= mid; i++) modify(a[i].x, a[i].y, -1);
	solve(l, l + l1 - 1, L, mid);
	solve(l + l1, r, mid + 1, R);
}
int main() {
	read(n), read(q);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			int x; read(x);
			a[++len] = (Node) {i, j, x};
		}
	sort(a + 1, a + len + 1);
	for (int i = 1; i <= q; i++)
		read(b[i].x1), read(b[i].y1), read(b[i].x2), read(b[i].y2), read(b[i].k);
	for (int i = 1; i <= q; i++) c[i] = i;
	solve(1, q, 1, len);
	for (int i = 1; i <= q; i++) cout << ans[i] << "\n";
	return 0;
}

posted @ 2018-08-14 22:20  谜のNOIP  阅读(103)  评论(0编辑  收藏  举报