题源链接:https://www.luogu.org/problem/P1972
思路
挺裸的区间查询题?借助这道题回忆一下树状数组最开始写了个状压线段树??脑子是真的不太好用
思考路径:
- 很自然想到要用前缀和。
- 如果要用前缀和相减查询,对于每次询问中,每个数字应该只有最后的位置有效。
- 按照上述思路,应该将查询按照右边界
r
从小到大排序,这样确保每次查询每个数字的位置都是最后一个有效位。(离线操作) - [单点修改 + 区间查询] 必然树状数组
over
Code
#include <bits/stdc++.h>
#define numm ch-48
#define pd putchar(' ')
#define pn putchar('\n')
#define pb push_back
#define fi first
#define se second
#define fre1 freopen("1.txt","r",stdin)
#define fre2 freopen("2.txt","w",stdout)
typedef long long int ll;
typedef long long int LL;
using namespace std;
template<typename T>
void read(T& res) {
bool flag = false;
char ch;
while (!isdigit(ch = getchar())) (ch == '-') && (flag = true);
for (res = numm; isdigit(ch = getchar()); res = (res << 1) + (res << 3) + numm);
flag && (res = -res);
}
template<typename T>
void write(T x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
//static auto _ = []()
//{
// ios::sync_with_stdio(false);
// cin.tie(0);
// return 0;
//}();
//
const int maxn = 1e6 + 5;
int n, m;
int t[maxn];
struct node {
int l, r;
int cnt, ans;
};
node q[maxn];
bool cmp(node a, node b) {
return a.r < b.r;
}
bool cmp2(node a, node b) {
return a.cnt < b.cnt;
}
int f[maxn] = { 0 };
int tr[maxn] = { 0 };
inline int lowbit(int x) {
return x & (-x);
}
void add(int x, int k) {
while (x <= n) {
tr[x] = tr[x] + k;
x = x + lowbit(x);
}
}
int getsum(int x) {
int ans = 0;
while (x >= 1) {
ans = ans + tr[x];
x = x - lowbit(x);
}
return ans;
}
int main() {
read(n);
for (int i = 1; i <= n; i++) {
read(t[i]);
}
read(m);
for (int i = 1; i <= m; i++) {
read(q[i].l); read(q[i].r);
q[i].cnt = i;
}
sort(q + 1, q + 1 + m, cmp);
int tmp = 0;
for (int i = 1; i <= m; i++) {
while (tmp < q[i].r) {
tmp++;
if (f[t[tmp]]) {
add(f[t[tmp]], -1);
}
f[t[tmp]] = tmp;
add(tmp, 1);
}
q[i].ans = getsum(q[i].r) - getsum(q[i].l - 1);
}
sort(q + 1, q + 1 + m, cmp2);
for (int i = 1; i <= m; i++) {
write(q[i].ans), pn;
}
return 0;
}