题意:
题目链接:http://acm.sdibt.edu.cn:8080/vjudge/problem/viewProblem.action?id=13725
给出n个数,问区间[L,R]中有多少不同的数。
思路:
经典题。
可以离线+树状数组,离线保存查询,按照r排序,用last数组保存每个数最接近当前询问r的位置。
也可以主席树,从右到左建树,pos保存每个数字的当前最左位置,每次在新版本的线段树中在当前位置+1,然后把旧版本中该树的位置-1.
代码:
离线+树状数组:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 10;
int n, q;
int bit[MAXN];
void add(int x, int y) {
while (x <= n) {
bit[x] += y;
x += x & -x;
}
}
int sum(int x) {
int res = 0;
while (x > 0) {
res += bit[x];
x -= x & -x;
}
return res;
}
struct node {
int l, r, id;
bool operator < (const node &rhs) const {
return r < rhs.r;
}
} que[MAXN];
int last[MAXN], a[MAXN], ans[MAXN];
int main() {
//freopen("in.txt", "r", stdin);
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
scanf("%d", &q);
for (int i = 1; i <= q; i++) {
scanf("%d%d", &que[i].l, &que[i].r);
que[i].id = i;
}
sort (que + 1, que + 1 + q);
for (int i = 1, j = 1; i <= q; i++) {
while (j <= que[i].r) {
add(j, 1);
if (last[a[j]]) add(last[a[j]], -1);
last[a[j]] = j;
j++;
}
ans[que[i].id] = sum(que[i].r) - sum(que[i].l - 1);
}
for (int i = 1; i <= q; i++)
printf("%d\n", ans[i]);
return 0;
}
主席树:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 33333;
struct node {
int ls, rs, sum;
} ns[MAXN * 40];
int rt[MAXN * 2], ct;
void cpy(int& now, int old) {
now = ++ct;
ns[now] = ns[old];
}
void build(int& now, int l, int r) {
now = ++ct;
ns[now].sum = 0;
if (l == r) return;
int m = (l + r) >> 1;
build(ns[now].ls, l, m);
build(ns[now].rs, m + 1, r);
}
void update(int& now, int old, int l, int r, int x, int y) {
cpy(now, old);
if (l == r) {
ns[now].sum += y;
return;
}
int m = (l + r) >> 1;
if (x <= m) update(ns[now].ls, ns[old].ls, l, m, x, y);
else update(ns[now].rs, ns[old].rs, m + 1, r, x, y);
ns[now].sum = ns[ns[now].ls].sum + ns[ns[now].rs].sum;
}
int query(int now, int old, int l, int r, int L, int R) {
if (L <= l && r <= R) return ns[now].sum - ns[old].sum;
int m = (l + r) >> 1, res = 0;
if (L <= m) res += query(ns[now].ls, ns[old].ls, l, m, L, R);
if (R > m) res += query(ns[now].rs, ns[old].rs, m + 1, r, L, R);
return res;
}
int pos[1000005], a[MAXN];
int main() {
//freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
ct = 0;
build(rt[2 * n + 1], 1, n);
memset(pos, -1, sizeof(pos));
for (int i = n; i >= 1; i--) {
update(rt[2 * i], rt[2 * i + 1], 1, n, i, 1);
if (pos[a[i]] == -1) update(rt[2 * i - 1], rt[2 * i], 1, n, i, 0);
else update(rt[2 * i - 1], rt[2 * i], 1, n, pos[a[i]], -1);
pos[a[i]] = i;
}
int q;
scanf("%d", &q);
while (q--) {
int L, R;
scanf("%d%d", &L, &R);
printf("%d\n", query(rt[2 * L - 1], rt[2 * n + 1], 1, n, L, R));
}
return 0;
}