[BZOJ3809]Gty的二逼妹子序列

[BZOJ3809]Gty的二逼妹子序列

试题描述

Autumn和Bakser又在研究Gty的妹子序列了!但他们遇到了一个难题。
对于一段妹子们,他们想让你帮忙求出这之内美丽度∈[a,b]的妹子的美丽度的种类数。
为了方便,我们规定妹子们的美丽度全都在[1,n]中。
给定一个长度为n(1<=n<=100000)的正整数序列s(1<=si<=n),对于m(1<=m<=1000000)次询问“l,r,a,b”,每次输出sl...sr中,权值∈[a,b]的权值的种类数。

输入

第一行包括两个整数n,m(1<=n<=100000,1<=m<=1000000),表示数列s中的元素数和询问数。
第二行包括n个整数s1...sn(1<=si<=n)。
接下来m行,每行包括4个整数l,r,a,b(1<=l<=r<=n,1<=a<=b<=n),意义见题目描述。
保证涉及的所有数在C++的int内。
保证输入合法。

输出

对每个询问,单独输出一行,表示sl...sr中权值∈[a,b]的权值的种类数。

输入示例

10 10
4 4 5 1 4 1 5 1 2 1
5 9 1 2
3 4 7 9
4 4 2 5
2 3 4 7
5 10 4 4
3 9 1 1
1 4 5 9
8 9 3 3
2 2 1 6
8 9 1 4

输出示例

2
0
0
2
1
1
1
0
1
2

数据规模及约定

见“输入

题解

莫队 + 树状数组。

不知为何这题还得卡常数。。。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <cmath>
using namespace std;

const int BufferSize = 1 << 16;
char buffer[BufferSize], *Head, *Tail;
inline char Getchar() {
	if(Head == Tail) {
		int l = fread(buffer, 1, BufferSize, stdin);
		Tail = (Head = buffer) + l;
	}
	return *Head++;
}
int read() {
	int x = 0, f = 1; char c = Getchar();
	while(!isdigit(c)){ if(c == '-') f = -1; c = Getchar(); }
	while(isdigit(c)){ x = x * 10 + c - '0'; c = Getchar(); }
	return x * f;
}

#define maxn 100010
#define maxq 1000010

int n, q, A[maxn], blid[maxn];

struct Que {
	int ql, qr, al, ar, id;
	Que() {}
	Que(int _1, int _2, int _3, int _4, int _5): ql(_1), qr(_2), al(_3), ar(_4), id(_5) {}
	bool operator < (const Que& t) const { return blid[ql] != blid[t.ql] ? blid[ql] < blid[t.ql] : qr < t.qr; }
} qs[maxq];

int tot[maxn], Ans[maxq];
int C[maxn];
void update(int x, int v) {
	for(; x <= n; x += x & -x) C[x] += v;
	return ;
}
int query(int x) {
	int sum = 0;
	for(; x; x -= x & -x) sum += C[x];
	return sum;
}

int main() {
	n = read(); q = read();
	int m = sqrt(n >> 1);
	for(int i = 1; i <= n; i++) {
		A[i] = read();
		blid[i] = (i - 1) / m + 1;
	}
	for(int i = 1; i <= q; i++) {
		int ql = read(), qr = read(), al = read(), ar = read();
		qs[i] = Que(ql, qr, al, ar, i);
	}
	sort(qs + 1, qs + q + 1);
	
	int l, r; l = r = tot[A[1]] = 1; update(A[1], 1);
	for(int i = 1; i <= q; i++) {
		while(r < qs[i].qr) {
			r++;
			if(++tot[A[r]] == 1) update(A[r], 1);
		}
		while(l > qs[i].ql) {
			l--;
			if(++tot[A[l]] == 1) update(A[l], 1);
		}
		while(r > qs[i].qr) {
			if(!--tot[A[r]]) update(A[r], -1);
			r--;
		}
		while(l < qs[i].ql) {
			if(!--tot[A[l]]) update(A[l], -1);
			l++;
		}
		Ans[qs[i].id] = query(qs[i].ar) - query(qs[i].al - 1);
	}
	
	for(int i = 1; i <= q; i++) printf("%d
", Ans[i]);
	
	return 0;
}
原文地址:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/6801387.html