【BZOJ4397】[Usaco2015 dec]Breed Counting【前缀和】【或莫队】【或线段树】【或可持久化线段树】

【题目链接】

数据结构学多了,看到题解发现3个前缀和就搞定了。弱智+2

另外也可以线段树,也可以3个主席树。。。


莫队:

/* Telekinetic Forest Guard */
#include 
#include 
#include 

using namespace std;

const int maxn = 100005, maxsqrtn = 316;

int n, m, num[maxn], cnt[5];

struct data {
	int l, r, id;

	bool operator < (const data &x) const {
		int a = l / maxsqrtn, b = x.l / maxsqrtn;
		return a != b ? a < b : r < x.r;
	}
} que[maxn], ans[maxn];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= n; i++) num[i] = iread();
	for(int i = 1; i <= m; i++) que[i].l = iread(), que[i].r = iread(), que[i].id = i;

	sort(que + 1, que + 1 + m);
	int l = 1, r = 0;
	for(int i = 1; i <= m; i++) {
		while(que[i].l < l) cnt[num[--l]]++;
		while(r < que[i].r) cnt[num[++r]]++;
		while(l < que[i].l) cnt[num[l++]]--;
		while(que[i].r < r) cnt[num[r--]]--;
		ans[que[i].id] = (data){cnt[1], cnt[2], cnt[3]};
	}

	for(int i = 1; i <= m; i++) printf("%d %d %d\n", ans[i].l, ans[i].r, ans[i].id);
	return 0;
}


你可能感兴趣的:(莫队算法,可持久化数据结构,线段树)