#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
const int N = 3e5 + 10;
vector<int> position;
vector<PII> add,query;
int a[N];
int find(int x)
{
int l = 0, r = position.size() - 1;
while(l < r)
{
int mid = l + r >> 1;
if(position[mid] >= x) r = mid;
else l = mid + 1;
}
return r + 1;//hope to start with 1
}
int main()
{
int n, m;
cin >> n >> m;
for(int i = 0; i < n; i ++)
{
int x, c;
cin >> x >> c;
add.push_back({x,c});
position.push_back(x);
}
for(int i = 0; i < m; i ++)
{
int l, r;
cin >> l >> r;
position.push_back(l);
position.push_back(r);
query.push_back({l,r});//因为询问和数字必须一起离散化收束才行 不然找不到收束后的位置
}
//离散化收束必要操作
sort(position.begin(),position.end());
position.erase(unique(position.begin(),position.end()),position.end());
//
for(auto it : add)//找到 add对中 要add的位置在已经收束完的离散集合里的位置 (有序的
{//然后对号入座到a数组里 这个集合是已经处理好的元素
int hash_position = find(it.first);// 5 8 90000 899990099
a[hash_position] += it.second; // 1 2 5 6
}
a[0] = 0;
for(int i = 1;i <= position.size();i++) a[i] += a[i - 1];//浅醉和
for(auto it : query)
{
int hash_position_l = find(it.first);//找到离散化之前的询问 对应收束后的位置
int hash_position_r = find(it.second);
cout << a[hash_position_r] - a[hash_position_l - 1] << endl;
}
return 0;
}
Acwing 802.区间和 离散化详解
最新推荐文章于 2025-08-02 10:34:45 发布