题解:P15452 [JOI 2026 SemiFinal] 宝石商 / Jeweler
题目传送门
思路
可能是前阵子树状数组学太多了,看到区间就想到了树状数组。
如果不会树状数组的话可以看其它题解或去学习一下树状数组。
这题用树状数组,先要弄清楚树状数组在维护什么,树状数组的插入和查询在干什么。
接下来的树状数组简称为 update(x, k),查询操作为 query(x)。
- 维护的值:
t_r = \displaystyle\sum_{i = 1}^{n}{(R_i = r) C_i} 。 - 插入操作:当
L_i \le T_j(1 \le i \le n, 1 \le j \le m) 时,update(R[i], C[i])。 - 查询操作:为了求
R_i \ge S_j 。需计算树状数组中[S_j,10^6] 的区间和」,即query(1000000) - query(S[j] - 1)(query(1000000)表示全部已插入的C_i 之和)。
为了让插入操作的寻找复杂度降低,可以把每个顾客按
把已经插入过的数量用
- 当
L_{cnt} \le T_j(1 \le cnt \le n, 1 \le j \le m) 时,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;
}