https://www.luogu.org/problemnew/show/P1972
题解
给定一段序列,每次询问一个区间[l,r]
里有多少个不相同的数。经典的做法便是,离线处理,将这些区间按照r
关键字从小到达排序。然后遍历这个序列,如果当前数x在之前的pre位置出现过,那么c[pre[x]]-1
,c[now[x]]+1
,当到达r
时,答案便是sum[r]-sum[l-1]
,其中sum[i]
是前缀和。
为什么这样是正确的呢?对于r >= now
假设pre < now
,因为如果一个数出现在pre
位置,也会出现在now
位置,但是出现在pre
位置只会对l<=pre
的区间[l,r]
有效,而出现在now
位置,则可对l <= now
的区间有效,明显前者是后者的子集,所以将其从pre
位置调换到now
位置,便可以解决r
之前的所有l
询问。
代码
#include <bits/stdc++.h>
using namespace std;
#define FOR0(a,b) for(int i = a; i < b; ++i)
#define FORE(a,b) for(int i = a; i <= b; ++i)
#define x first
#define y second
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1000000+10;
int c[maxn],n;
int lowbit(int x) {
return x&(-x);
}
void add(int x, int d) {
while(x <= 1000000) {
c[x] += d;
x += lowbit(x);
}
}
int sum(int x) {
int ret = 0;
while(x) {
ret += c[x];
x -= lowbit(x);
}
return ret;
}
inline int read()
{
int k=0;
char f=1;
char c=getchar();
for(;!isdigit(c);c=getchar() )
if(c=='-')
f=-1;
for(;isdigit(c);c=getchar() )
k=k*10+c-'0';
return k*f;
}
struct Cor{
int l,r,i;
bool operator < (const Cor& rhs) const {
return r < rhs.r;
}
}cor[maxn];
int ans[maxn];
int a[maxn],q,vis[maxn];
int main() {
n = read();
for(int i = 1; i <= n; ++i)
a[i] = read();
scanf("%d", &q);
int l,r;
for(int i = 0; i < q; ++i) {
cor[i].l = read(); cor[i].r = read();
cor[i].i = i;
}
sort(cor, cor+q);
int cur = 0;
l = 1;
for(int i = 0; i < q; ++i) {
for(int j = l; j <= cor[i].r; ++j) {
add(j,1);
if(vis[a[j]])
add(vis[a[j]],-1);
vis[a[j]] = j;
}
l = cor[i].r+1;
ans[cor[i].i] = sum(cor[i].r)-sum(cor[i].l-1);
}
for(int i = 0; i < q; ++i)
cout << ans[i] << endl;
return 0;
}