题目描述
模板题:离散化
C++代码
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 3e5 + 10;
int n, m, l, r, c, x;
int a[N], s[N];
vector<int> alls;
vector<PII> adds;
vector<PII> querys;
int find(int x){
int l = 0, r = alls.size() - 1;
while(l < r){
int mid = l + r >> 1;
if(alls[mid] >= x)
r = mid;
else
l = mid + 1;
}
return l + 1;
}
int main(){
cin >> n >> m;
for(int i = 0; i < n; i++){
cin >> x >> c;
alls.push_back(x);
adds.push_back({x, c});
}
for(int i = 0; i < m; i++){
cin >> l >> r;
alls.push_back(l);
alls.push_back(r);
querys.push_back({l, r});
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
for(auto item : adds){
int index = find(item.first);
a[index] += item.second;
}
for(int i = 1; i <= alls.size(); i++)
s[i] += s[i - 1] + a[i];
for(auto item : querys){
l = find(item.first);
r = find(item.second);
cout << s[r] - s[l - 1] << endl;
}
}