0
点赞
收藏
分享

微信扫一扫

luoguP4396 [AHOI2013]作业(莫队+值域分块)


​​传送门​​

思路

与上题​类似,本题是求数的个数以及数的种类数。
多记录一个数组表示每一块的数的个数。

代码:

// Problem: P4396 [AHOI2013]作业
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P4396
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// Author:Cutele
//
// Powered by CP Editor (https://cpeditor.org)

#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 write(ll x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}

#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 mod){ll res = 1;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}

const int maxn=100000+10,maxm=1000000+10;

int n,m,a[maxn];
struct node{
int l,r,a,b,id;
}q[maxm];

int L[1100],R[1100],sum[1100],col[maxn],pos[maxn],tmp[maxn];
PII ans[maxm];
bool cmp(node a,node b){
if(pos[a.l]==pos[b.l]) return a.r<b.r;
return pos[a.l]<pos[b.l];
}

void add(int id){
int t=a[id];
col[t]++;
tmp[pos[t]]++;
if(col[t]==1) sum[pos[t]]++;
}

void del(int id){
int t=a[id];
col[t]--;
tmp[pos[t]]--;
if(!col[t]) sum[pos[t]]--;

}

PII qask(int l,int r){
PII res;
int bl=pos[l],br=pos[r];
if(bl==br){
rep(i,l,r) res.first+=col[i],res.second+=(col[i]>0);
return res;
}
rep(i,bl+1,br-1) res.first+=tmp[i],res.second+=sum[i];
rep(i,l,R[bl]) res.first+=col[i],res.second+=(col[i]>0);
rep(i,L[br],r) res.first+=col[i],res.second+=(col[i]>0);
return res;
}

int main(){
n=read,m=read;
int block=sqrt(n);
memset(L,0x3f,sizeof L);
rep(i,1,n){
a[i]=read;
pos[i]=(i-1)/block+1;
L[pos[i]]=min(L[pos[i]],i);
R[pos[i]]=max(R[pos[i]],i);
}
rep(i,1,m){
q[i].l=read,q[i].r=read,q[i].a=read,q[i].b=read,q[i].id=i;
}
sort(q+1,q+1+m,cmp);

int nowl=0,nowr=0;

rep(i,1,m){
int ql=q[i].l,qr=q[i].r;
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].a,q[i].b);
}

rep(i,1,m) printf("%d %d\n",ans[i].first,ans[i].second);




return 0;
}


举报

相关推荐

0 条评论