离散化
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 3e5 + 10;
LL n, m, a[N], s[N];
int main(){
ios::sync_with_stdio(false);cin.tie(0);
cin >> n >> m;
vector <LL> num;
vector <pair <LL, LL>> add, q;
for (int i = 0; i < n; i ++ ){
LL x, c;
cin >> x >> c;
num.push_back(x);
add.push_back({x, c});
}
for (int i = 0; i < m; i ++ ){
LL l, r;
cin >> l >> r;
q.push_back({l, r});
num.push_back(l);
num.push_back(r);
}
sort(num.begin(), num.end());
num.erase(unique(num.begin(), num.end()), num.end());
for (auto x : add){
LL t = lower_bound(num.begin(), num.end(), x.first) - num.begin() + 1;
a[t] += x.second;
}
for (int i = 1; i <= (int)num.size(); i ++ )
s[i] = s[i - 1] + a[i];
for (auto x : q){
LL l = lower_bound(num.begin(), num.end(), x.first) - num.begin() + 1;
LL r = lower_bound(num.begin(), num.end(), x.second) - num.begin() + 1;
cout << s[r] - s[l - 1] << "\n";
}
return 0;
}
自定义 unique 函数
vector <int> :: iterator unique(vector <int> &a){
int j = 0;
for (int i = 0; i < a.size(); i++)
if (!i || a[i] != a[i - 1])
a[j++] = a[i];
return a.begin() + j;
}