区间和:
#include <iostream> #include <vector> #include <algorithm> using namespace std; const int N = 300000; int a[N],s[N]; typedef pair<int, int> PII; vector<int> alls; vector<PII> add,query; 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 r + 1; } int main() { int n,m; cin>>n>>m; while(n--) { int x,c; cin>>x>>c; alls.push_back(x); add.push_back({x,c}); } while(m--) { int l,r; cin>>l>>r; alls.push_back(l); alls.push_back(r); query.push_back({l,r}); } sort(alls.begin(), alls.end()); alls.erase(unique(alls.begin(), alls.end()), alls.end()); for(auto item : add) { int x = find(item.first); a[x] += item.second; } for(int i = 1;i<=alls.size();i++) s[i] = s[i-1] + a[i]; for(auto item : query) { int l = find(item.first), r = find(item.second); cout<<s[r] - s[l-1]<<endl; } }
将原来2 * 10^9的数量级离散化成3*10^5,
x c l r
1 2 1 3
3 6 4 6
7 5 7 8
alls: 1 3 7 1 3 4 6 7 8
sort: 1 1 3 3 4 6 7 7 8
去重:1 3 4 6 7 8 --->x
把add里面的second变量加到数组里面来,接着结合前缀和的知识,求出前缀和。
PS:二分查找里面find返回的是第一个大于等于x的位置再+1,因为前缀和要从1开始,即s[i] = s[i-1] + a[i];
原文:https://www.cnblogs.com/longxue1991/p/12658886.html