其实是很水的一道题,但是由于我没有算好ans的数组大小导致一直wa。。
就是莫队分块,然后统计一下不同的个数。我们只需要看一个数出现是否>0来计算即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// Author: levil #include<bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int,int> pii; const int N = 3e4+5; const int M = 2e5+5; const LL Mod = 199999; #define rg register #define pi acos(-1) #define INF 1e9 #define CT0 cin.tie(0),cout.tie(0) #define IO ios::sync_with_stdio(false) #define dbg(ax) cout << "now this num is " << ax << endl; namespace FASTIO{ inline LL read(){ LL x = 0,f = 1;char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -1;c = getchar();} while(c >= '0' && c <= '9'){x = (x<<1)+(x<<3)+(c^48);c = getchar();} return x*f; } void print(int x){ if(x < 0){x = -x;putchar('-');} if(x > 9) print(x/10); putchar(x%10+'0'); } } using namespace FASTIO; void FRE(){ /*freopen("data1.in","r",stdin); freopen("data1.out","w",stdout);*/} int a[N],vis[1000005],ans[M],cnt = 0;//cnt统计不同数字个数 struct Node{int L,r,bl,id;}p[M]; bool cmp(Node a,Node b) { if(a.bl != b.bl) return a.L < b.L; if(a.bl&1) return a.r < b.r; return a.r > b.r; } void del(int x) { x = a[x]; if(vis[x] == 1) cnt--; vis[x]--; } void add(int x) { x = a[x]; if(vis[x] == 0) cnt++; vis[x]++; } int main() { int n;n = read(); for(rg int i = 1;i <= n;++i) a[i] = read(); int q;q = read(); int blsize = sqrt(n); for(rg int i = 1;i <= q;++i) { p[i].L = read(),p[i].r = read(); p[i].id = i,p[i].bl = (p[i].L-1)/blsize+1; } sort(p+1,p+q+1,cmp); int L = 1,r = 0; for(rg int i = 1;i <= q;++i) { while(L < p[i].L) del(L++); while(L > p[i].L) add(--L); while(r < p[i].r) add(++r); while(r > p[i].r) del(r--); ans[p[i].id] = cnt; } for(rg int i = 1;i <= q;++i) printf("%d ",ans[i]); // system("pause"); }