题目链接:hdu3333
题目大意:给一段n长度的数字序列,以及q长度的区间询问,问区间不同数字大小之和。
解题思路:跟区间数种类这题类似只不过种类数改成不同种类数字之和。树状数组改成维护不同种类数字之和。注意数字之和会爆int,C数组设置成long long
AC代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <utility>
using namespace std;
typedef long long ll;
const int Vmaxn = (int)3e4+5;
const int Qmaxn = (int)1e5+5;
struct Node {
int l,r;
int id;
bool operator < (const Node& A) const {
return this->r < A.r;
}
};
ll c[Vmaxn],ans[Qmaxn];
int n,q,val[Vmaxn];
Node qry[Qmaxn];
map<int, int > vis;
inline int lowbit (int x) {
return x & (-x);
}
void add (int idx, ll num) {
while (idx <= Vmaxn) {
c[idx] += num;
idx += lowbit(idx);
}
}
ll get_sum (int idx) {
ll ans = 0;
while (idx > 0) {
ans += c[idx];
idx -= lowbit(idx);
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int T;
cin >> T;
for (int k = 1; k <= T; k++) {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> val[i];
}
cin >> q;
for (int i = 1; i <= q; i++) {
cin >> qry[i].l >> qry[i].r;
qry[i].id = i;
}
sort(qry + 1, qry + 1 + q);
memset(c, 0, sizeof(c));
vis.clear();
int point = 1;
for (int i = 1; i <= q; i++) {
while (point <= qry[i].r) { // 更新
if(vis.find(val[point]) != vis.end()) {
add(vis[val[point]], -val[point]);
}
vis[val[point]] = point;
add(vis[val[point]], val[point]);
point ++; //注意别遗漏
}
ans[qry[i].id] = get_sum(qry[i].r) - get_sum(qry[i].l- 1);
}
for (int i = 1; i <= q; i++) {
cout << ans[i] << '\n';
}
}
return 0;
}