给出一个长度为n 的数列\(a_{1},a_{2},...,a_{n}\);
有\(q\)个询问,每个询问给出数对\((i,j)\);
需要你给出\(a_{i},a_{i+1}a,...,a_{j}\)这一段中有多少不同的数字.
#include<bits/stdc++.h>
using namespace std;
const int M=1010000;
int n,m,a[M],belong[M],size,bnum,cnt[M],ans[M],now;
#define isdigit(x) ((x) >= '0' && (x) <= '9')
int read() {
int res = 0;
char c = getchar();
while(!isdigit(c)) c = getchar();
while(isdigit(c)) res = (res << 1) + (res << 3) + c - 48, c = getchar();
return res;
}
void pr(int x)
{
if(x/10) pr(x/10);
putchar(x%10 +'0');
}
struct query
{
int l,r,id;
}q[M];
bool cmp(query i,query j)
{
// return belong[i.l]==belong[j.l]? i.r<j.r : belong[i.l]<belong[j.l];
return (belong[i.l] ^ belong[j.l])? (belong[i.l]<belong[j.l]) : ((belong[i.l] & 1)? i.r<j.r:i.r>j.r );
}
int main()
{
n=read();
for(int i=1;i<=n;i++)a[i]=read();
int qq=read();
for(int i=1;i<=qq;i++)
{
q[i].id=i;
q[i].l=read();
q[i].r=read();
}
size=sqrt(n);
bnum= ceil((double)n/size);
for(int i=1;i<=bnum;i++)
for(int j=(i-1)*size+1;j<=i*size;j++)
belong[j]=i;
sort(q+1,q+qq+1,cmp);
int L=1,R=0,ql=0,qr=0;
for(int i=1;i<=qq;i++)
{
ql=q[i].l;qr=q[i].r;
while(L<ql) now -= !--cnt[a[L++]];
while(L>ql) now += !cnt[a[--L]]++;
while(R<qr) now += !cnt[a[++R]]++;
while(R>qr) now -= !--cnt[a[R--]];
ans[q[i].id]=now;
}
for(int i=1;i<=qq;i++)pr(ans[i]),putchar('\n');
return 0;
}
原文:https://www.cnblogs.com/kion/p/11817143.html