AcWing 802. 区间和
原题链接
简单
作者:
阿飞被注册了
,
2021-06-11 21:01:43
,
所有人可见
,
阅读 247
C++ 代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
typedef pair<int, int> PII;
const int N = 3e5 + 10;
int a[N];//最终的数组
vector<int> alls;//存所有出现的坐标
vector<PII> sumup, add;//sumup:存储最后加和区间; add:存储在哪个位置加上了那个数
int find(int x)//利用二分找出x在所有坐标alls中的位置--离散化即映射至较小的区间
{
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;
for(int i = 0; i < n; i++)
{
int x, c;
cin >> x >> c;
alls.push_back(x);
add.push_back({x, c});
}
for(int i = 0; i < m; i++)
{
int l, r;
cin >> l >> r;
sumup.push_back({l, r});
alls.push_back(l);
alls.push_back(r);
}
//排序去重。
//unique返回的是数组中最后一个不重复值的位置(迭代器)
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
//插入操作
for(auto x : add)
a[find(x.first)] += x.second;
//处理前缀和
for(int i = 1; i <= alls.size(); i++)
a[i] += a[i-1];
for(auto x : sumup)
{
int l = find(x.first), r = find(x.second) ;
cout << a[r] - a[l-1] << endl;
}
return 0;
}