【题目链接】
【前置技能】
- 线段树
【题解】
- 先预处理出 n x t nxt nxt数组, n x t [ i ] nxt[i] nxt[i]表示下一个和 i i i号位颜色相同的的位置。考虑把询问离线下来,按左端点从小到大排序。对于每一个左端点开始的区间,让每种颜色第二次出现的位置做出一点贡献。左端点为 1 1 1的可以简单处理好,那么每次左端点向右移一格的时候只要将线段树 n x t [ i ] nxt[i] nxt[i]位减一, n x t [ n x t [ i ] ] nxt[nxt[i]] nxt[nxt[i]]位加一。询问的时候询问区间和即可。
- 时间复杂度 O ( N l o g N ) O(NlogN) O(NlogN)
【代码】
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define LL long long
#define MAXN 2000010
using namespace std;
int n, c, m, nxt[MAXN], col[MAXN], w[MAXN], ans[MAXN];
struct que{int l, r, id;}q[MAXN];
template <typename T> void chkmin(T &x, T y){x = min(x, y);}
template <typename T> void chkmax(T &x, T y){x = max(x, y);}
template <typename T> void read(T &x){
x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
x *= f;
}
bool cmp(que a, que b){
return a.l < b.l;
}
struct Binary_Indexed_Tree{
int a[MAXN], n;
void init(int x){
n = x;
}
int low(int x){return x & (-x);}
void modify(int p, int d){
for (int i = p; i <= n; i += low(i))
a[i] += d;
}
int query(int l, int r){
int ret = 0;
for (int i = r; i; i -= low(i))
ret += a[i];
for (int i = l - 1; i; i -= low(i))
ret -= a[i];
return ret;
}
}bit;
int main(){
read(n), read(c), read(m);
for (int i = 1; i <= n; ++i)
read(w[i]);
nxt[n + 1] = n + 1;
for (int i = 1; i <= c; ++i)
col[i] = n + 1;
for (int i = n; i >= 1; --i)
nxt[i] = col[w[i]], col[w[i]] = i;
for (int i = 1; i <= m; ++i)
read(q[i].l), read(q[i].r), q[i].id = i;
sort(q + 1, q + 1 + m, cmp);
bit.init(n + 1);
memset(col, 0, sizeof(col));
for (int i = 1; i <= n; ++i){
if (col[w[i]]) continue;
bit.modify(nxt[i], 1);
col[w[i]] = 1;
}
int cur = 1;
for (int T = 1; T <= m; ++T){
int l = q[T].l, r = q[T].r;
for (; cur < l; ++cur){
bit.modify(nxt[cur], -1);
bit.modify(nxt[nxt[cur]], 1);
}
ans[q[T].id] = bit.query(l, r);
}
for (int i = 1; i <= m; ++i)
printf("%d\n", ans[i]);
return 0;
}