离散化acwing802区间和

#include<iostream>
using namespace std;
const int N = 300010;
int a[N],s[N];
//a用于存放数据被离散化后的数据
//s用于记录a的前缀和 
#include <vector>
#include <algorithm>
vector<pair<int,int>>add,query;//add 用于存放离散后的小下标 从0开始到n-1
//query用于存放每次询问的l ,r 
vector<int>alls;//alls用于存放大下标 
int n,m;
//find用于查找下标 
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()
{
	cin>> n >> m;
	for(int i = 1; i <= n; i++){
		int x, c;
		cin >> x >> c;
		alls.push_back(x);
		add.push_back({x,c});
	}
	 
	for(int j = 1; j <= m; j++){
		int l, r;
		cin >> l >> r;
		alls.push_back(l);
		alls.push_back(r);
		query.push_back({l,r});
	}
	
	sort(alls.begin(),alls.end());//排序是因为find函数是基于二分查找 
	alls.erase(unique(alls.begin(),alls.end()),alls.end());//去重 alls中存放的是下标 可能有重复的下标 
	
	for(auto item:add){//遍历add first为大下标 second为需要加上的值c  
		//先找到存放大下标下的小下标 
		//再给对应的赋值 
		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){
		//此处与上面一样 first与second 存放的都是大下标 分别代表l,r所以需要查找两次 
		int l = find(item.first);
		int r = find(item.second);
		cout<<s[r] - s[l-1]<<endl;
	}
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值