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;
}

博客详细介绍了如何运用树状数组解决区间种类数问题。通过离线处理区间查询,按照区间起点排序,利用树状数组维护前缀和,确保正确计算每个区间内的不重复整数。解释了为何这种方法能够正确处理所有询问,同时提供了问题的解题思路和代码实现。
690

被折叠的 条评论
为什么被折叠?



