HDU 3333 Turing Tree (树状数组)

时间:2023-12-25 22:40:13

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3333

题意就是询问区间不同数字的和。

比较经典的树状数组应用。

 //#pragma comment(linker, "/STACK:102400000, 102400000")
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
typedef pair <int, int> P;
const int N = 1e5 + ;
struct query {
int l, r, pos;
bool operator <(const query &cmp) const {
return r < cmp.r;
}
}q[N];
int a[];
LL bit[], ans[N];
map <int, int> mp; void update(int i, LL val) {
for( ; i <= ; i += (i&-i))
bit[i] += val;
} LL sum(int i) {
LL s = ;
for( ; i >= ; i -= (i&-i))
s += (LL)bit[i];
return s;
} int main()
{
int t, n, m;
scanf("%d", &t);
while(t--) {
memset(bit, , sizeof(bit));
mp.clear();
scanf("%d", &n);
for(int i = ; i <= n; ++i) {
scanf("%d", a + i);
}
scanf("%d", &m);
for(int i = ; i <= m; ++i) {
scanf("%d %d", &q[i].l, &q[i].r);
q[i].pos = i;
}
sort(q + , q + m + );
int index = ;
for(int i = ; i <= n; ++i) {
if(mp.find(a[i]) != mp.end()) { //a[i]曾经出现过
update(mp[a[i]], (LL)-a[i]);
}
mp[a[i]] = i;
update(i, a[i]);
while(q[index].r == i && index <= m) {
ans[q[index].pos] = sum(q[index].r) - sum(q[index].l - );
++index;
}
}
for(int i = ; i <= m; ++i) {
printf("%lld\n", ans[i]);
}
}
return ;
}