【分块】 HDOJ 5213 Lucky

可以用一个简单的技巧将问题转化为莫队算法来做。

#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 1000005
#define maxm 1000005
#define eps 1e-12
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
//#define ls o<<1
//#define rs o<<1 | 1
//#define lson o<<1, L, mid 
//#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
// head

struct node
{
	int l, r, id, val, sn;
	node() {}
	node(int l, int r, int id, int val, int sn) : l(l), r(r), id(id), val(val), sn(sn) {}
}q[maxn];

int cmp(node a, node b)
{
	if(a.sn != b.sn) return a.sn < b.sn;
	if(a.r != b.r) return a.r < b.r;
	return a.l < b.l;
}

int res[30005];
int c[60005];
int a[maxn];
int n, m, k, ans;

void del(int x)
{
	c[x]--;
	if(k >= x) ans -= c[k - x];
}

void add(int x)
{
	if(k >= x) ans += c[k - x];
	c[x]++;
}

void work()
{
	scanf("%d", &k);
	int sn = 180, l1, l2, r1, r2;
	memset(c, 0, sizeof c);
	memset(res, 0, sizeof res);
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
	a[0] = 60001;
	ans = 0;
	scanf("%d", &m);
	int cnt = 0;
	for(int i = 1; i <= m; i++) {
		scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
		q[cnt++] = node(l1, r2, i, 1, l1 / sn);
		q[cnt++] = node(r1+1, l2-1, i, 1, (r1+1) / sn);
		q[cnt++] = node(l1, l2-1, i, -1, l1 / sn);
		q[cnt++] = node(r1+1, r2, i, -1, (r1+1) / sn);
	}
	sort(q, q+cnt, cmp);
	int l = 0, r = 0;
	for(int i = 0; i < cnt; i++) {
		while(q[i].l < l) add(a[--l]);
		while(q[i].r > r) add(a[++r]);
		while(q[i].l > l) del(a[l++]);
		while(q[i].r < r) del(a[r--]);
		res[q[i].id] += q[i].val * ans;
	}
	for(int i = 1; i <= m; i++) printf("%d\n", res[i]);
}

int main()
{
	while(scanf("%d", &n)!=EOF) work();

	return 0;
}


你可能感兴趣的:(分块)