luoguP4396 [AHOI2013]作业

https://www.luogu.org/problemnew/show/P4396

简单的莫队+树状数组,但博主被卡常了,不保证代码在任何时候都能AC

#include <bits/stdc++.h>
using namespace std;

template <typename T>
inline void read(T &f) {
	f = 0; T fu = 1; char c = getchar();
	while (c < '0' || c > '9') {if (c == '-') fu = -1; c = getchar();}
	while (c >= '0' && c <= '9') {f = (f << 3) + (f << 1) + (c & 15); c = getchar();}
	f *= fu;
}

const int N = 3e5 + 5;

int cnt[N], f[2][N], a[N], B[N], pre[N], Ans[N][2];
int n, m, block, len;

struct ele {
	int l, r, _l, _r, id;
	bool operator < (const ele A) const {
		return B[l] < B[A.l] || (B[l] == B[A.l] && r < A.r);
	}
}Q[N];

int lowbit(int x) {return x & -x;}
void add(int *f, int x, int y) {for(int i = x; i <= n; i += lowbit(i)) f[i] += y;}
int query(int *f, int x) {int ans = 0; for(int i = x; i; i -= lowbit(i)) ans += f[i]; return ans;}
void change(int x, int y) {
	if(y == 1) {
		add(f[0], x, 1);
		if(cnt[x] == 0) add(f[1], x, 1);
		cnt[x]++;
	} else {
		add(f[0], x, -1);
		cnt[x]--;
		if(cnt[x] == 0) add(f[1], x, -1);
	}
}

int main() {
	cin >> n >> m; block = n / (sqrt(m * 2 / 3) + 1) + 1;
	for(int i = 1; i <= n; i++) B[i] = (i - 1) / block + 1;
	for(int i = 1; i <= n; i++) read(a[i]), pre[++len] = a[i];
	for(int i = 1; i <= m; i++) {
		int l, r, L, R;
		read(l); read(r);
		read(L); read(R);
		Q[i] = (ele) {l, r, L, R, i};
		pre[++len] = L, pre[++len] = R;
	}
	sort(pre + 1, pre + len + 1);
	len = unique(pre + 1, pre + len + 1) - pre - 1;
	for(int i = 1; i <= m; i++) {
		Q[i]._l = lower_bound(pre + 1, pre + len + 1, Q[i]._l) - pre;
		Q[i]._r = lower_bound(pre + 1, pre + len + 1, Q[i]._r) - pre;
	}
	for(int i = 1; i <= n; i++) a[i] = lower_bound(pre + 1, pre + len + 1, a[i]) - pre;
	sort(Q + 1, Q + m + 1);
	int l = 1, r = 0;
	for(int i = 1; i <= m; i++) {
		while(r < Q[i].r) change(a[++r], 1);
		while(l > Q[i].l) change(a[--l], 1);
		while(r > Q[i].r) change(a[r--], -1);
		while(l < Q[i].l) change(a[l++], -1);
		Ans[Q[i].id][0] = query(f[0], Q[i]._r) - query(f[0], Q[i]._l - 1);
		Ans[Q[i].id][1] = query(f[1], Q[i]._r) - query(f[1], Q[i]._l - 1);
	}
	for(int i = 1; i <= m; i++) printf("%d %d\n", Ans[i][0], Ans[i][1]);
	return 0;
}
posted @ 2018-09-11 16:07  LJC00118  阅读(138)  评论(0编辑  收藏  举报
/*
*/