题目传送门
思路
可能是前阵子树状数组学太多了,看到区间就想到了树状数组。但是这题是橙欸,那看来我的思路应该不会重。
如果不会树状数组的话可以看其它题解或去学习一下树状数组。
这题用树状数组,先要弄清楚树状数组在维护什么,树状数组的插入和查询在干什么。
接下来的树状数组简称为 ,插入操作为 update(x, k),查询操作为 query(x)。
- 维护的值:。
- 插入操作:当 时,
update(R[i], C[i])。 - 查询操作:为了求 。需计算树状数组中 的区间和」,即
query(1000000) - query(S[j] - 1)(query(1000000)表示全部已插入的 之和)。
为了让插入操作的寻找复杂度降低,可以把每个顾客按 排序,所有查询按 排序。每次插入后,下次插入只需要从上次插入后一个开始找即可。
把已经插入过的数量用 存储,插入操作可以改为:
- 当 时,
update(R[cnt], C[cnt++])。
输出的时候只需要把答案按照输入时的顺序输出即可。
#include <bits/stdc++.h>
using namespace std;
struct Tree {
long long tree[1000010];
int len;
Tree(int n) {
len = n;
memset(tree, 0, sizeof(tree));
}
void update(int i, long long val) { //树状数组修改
for (; i <= len; i += (i & -i)) {
tree[i] += val;
}
}
long long query(int i) { //树状数组查询
long long res = 0;
for (; i > 0; i -= (i & -i)) {
res += tree[i];
}
return res;
}
};
long long ans[300010];
struct customer {
int l, r;
long long c;
} l[300010];
struct query {
int s, t, idx;
} q[300010];
bool cmp1(customer a, customer b) {
return a.l < b.l;
}
bool cmp2(query a, query b) {
return a.t < b.t;
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> l[i].l >> l[i].r >> l[i].c;
}
sort(l + 1, l + n + 1, cmp1);
int m;
cin >> m;
for (int i = 1; i <= m; i++) {
cin >> q[i].s >> q[i].t;
q[i].idx = i;
}
sort(q + 1, q + m + 1, cmp2);
Tree t(1000000);
int cnt = 1;
for (int i = 1; i <= m; i++) {
while (cnt <= n && l[cnt].l <= q[i].t) { //插入操作
t.update(l[cnt].r, l[cnt].c);
cnt++;
}
ans[q[i].idx] = t.query(1000000) - t.query(q[i].s - 1); //查询操作
}
for (int i = 1; i <= m; i++) {
cout << ans[i] << endl; //按原顺序输出
}
return 0;
}