离散化就是将很稀疏的点映射到1,2,3,4,5.....
原理就是: 二分将a[i]映射到i或者i+1
https://www.acwing.com/problem/content/804/
code:
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,int> PII;
vector<int> alls;
const int N = 3e5 + 10;
int a[N],s[N];
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;
}
vector<PII> add,query;
int main()
{
int n,m;
scanf("%d %d",&n,&m);
while(n--){
int x,c;
add.push_back({x,c});
alls.push_back(x);
}
while(m -- ){
int l,r;
query.push_back({l,r});
alls.push_back(l);
alls.push_back(r);
}
sort(alls.begin(),alls.end());
alls.erase(unique(alls.begin(),alls.end()),alls.end());
//离散化后数组赋值
for(int i = 0 ; i <add.size() ; i ++){
a[find(add[i].first)] += add[i].second;
}
//求离散化数组前缀和
for(int i = 1; i <= alls.size(); i++){
s[i]=s[i-1] + a[i];
}
for(auto i : query){
int l = find(i.first), r = find(i.second);
int ans = s[r] - s[l - 1];
printf("%d\n",ans);
}
return 0;
}