Interval Sum
vector<int> all;
vector<pair<int, int> > add, query;
const int N = 3e5 + 5; // Attention! When worst case that l, r, x all different, we need 3e5 to store though n, m are no bigger than 1e5.
int a[N], sum[N];
int find(int x) {
int l = 0, r = all.size() - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (all[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l + 1;
}
int main() {
IOS;
int n, m;
cin >> n >> m;
for (int i = 0; i < n; ++i) {
int x, c;
cin >> x >> c;
add.push_back(make_pair(x, c));
all.push_back(x);
}
for (int i = 0; i < m; ++i) {
int l, r;
cin >> l >> r;
query.push_back(make_pair(l, r));
all.push_back(l);
all.push_back(r);
}
sort(all.begin(), all.end());
all.erase(unique(all.begin(), all.end()), all.end());
for (int i = 0; i < n; ++i) {
int x = find(add[i].first);
a[x] += add[i].second;
}
for (int i = 1; i <= (int)all.size(); ++i) {
sum[i] = sum[i - 1] + a[i];
}
for (auto i: query) {
int l = find(i.first), r = find(i.second);
cout << sum[r] - sum[l - 1] << '\n';
}
return 0;
}
Description
Given an infinite number axis with all points have value 0, oprate n times, each add point \(p_i\) by \(x_i\). Then m queries, each ask the interval sum of interval \([l, r]\). Interval sum is the sum of point value from \(l\) to \(r\).
Discretization
Establishing the mapping relationship between a number sequence and natural numbers is what discretization does. Usually we can sort the value array, then erase the duplicates, then we use \(Binary-Search\) to find the new index. After discretization, we can implement \(pre-sum\) algorithm to solve the problem.
标签:int,sum,back,mid,离散,add,push,一题,每日 From: https://www.cnblogs.com/whose-dream/p/16882513.html