HDU6959 2021多校 zoto(莫队+分块)

link

思路:

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

inline void out(ll x){
	if (x < 0) x = ~x + 1, putchar('-');
	if (x > 9) out(x / 10);
	putchar(x % 10 + '0');
}

inline void write(ll x){
	if (x < 0) x = ~x + 1, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
	puts("");
}

#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)
const int maxn=100000+100;


ll n,m,fx[maxn];
struct node{
	ll x1,y1,x2,y2,id;
}q[maxn];
ll ans[maxn];
ll num,block,belong[maxn],sum[maxn],l[maxn],r[maxn],w[maxn];
ll siz[maxn];

bool cmp(node a,node b){
	if(a.x1/block==b.x1/block) return a.x2<b.x2;
	return a.x1<b.x1;
}

void build(){
	block=sqrt(n);
	num=n/block;
	if(n%block) num++;
	for(int i=1;i<=num;i++){
		l[i]=(i-1)*block+1;
		r[i]=min(n,i*block);
	}
	rep(i,1,n){
		belong[i]=(i-1)/block+1;
		sum[belong[i]]+=w[i];
	}
}

void add(int x){
	int t=fx[x];
	siz[t]++;
	if(siz[t]==1){
		w[t]++;
		sum[belong[t]]++;
	}
}

void del(int x){
	int t=fx[x];
	siz[t]--;
	if(!siz[t]){
		w[t]--;
		sum[belong[t]]--;
	}
}

int qask(int ql,int qr){
	int res=0;
	int bl=belong[ql],br=belong[qr];
	if(bl==br){
		rep(i,ql,qr) res+=w[i];
		return res;
	}
	rep(i,bl+1,br-1) res+=sum[i];
	rep(i,ql,r[bl]) res+=w[i];
	rep(i,l[br],qr) res+=w[i];
	return res;
}

int main(){
	int _=read;
	while(_--){
		memset(sum,0,sizeof sum);
		memset(siz,0,sizeof siz);
		memset(w,0,sizeof w);
		n=read,m=read;
		rep(i,1,n) fx[i]=read+1;
		rep(i,1,m){
			q[i].x1=read,q[i].y1=read+1,q[i].x2=read,q[i].y2=read+1;
			q[i].id=i;
		}
		build();
		sort(q+1,q+1+m,cmp);
		int nowl=0,nowr=0;
		rep(i,1,m){
			int ql=q[i].x1,qr=q[i].x2;
			while(nowl<ql) del(nowl++);
			while(nowl>ql) add(--nowl);
			while(nowr>qr) del(nowr--);
			while(nowr<qr) add(++nowr);
			ans[q[i].id]=qask(q[i].y1,q[i].y2);
		}
		rep(i,1,m) printf("%lld\n",ans[i]);
	}
	return 0;
} 













posted @ 2021-07-22 19:09  OvO1  阅读(65)  评论(0编辑  收藏  举报