802. 区间和

离散化
把整型区间的数映射到十万左右
1.去重
2.二分查找

#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 3e5+7; 
typedef pair<int, int> PII;
vector<PII> add, query; //添加的值 和查询的区间 
vector<int> alls; //所有的坐标点 
int a[N], s[N]; //原数组和前缀和数组 
int n, m;
int find(int x){ //使用二分查找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; //从1开始映射 
} 
int main(){
	cin>>n>>m;
	int x, c;
	for(int i = 0; i < n; i++){
		cin>>x>>c;
		add.push_back({x,c});
		alls.push_back(x); //先把下标放入向量中 统一离散化 
	}
	int u, v;
	for(int i = 0; i < m; i++){
		cin>>u>>v;
		query.push_back({u, v});
		alls.push_back(u);
		alls.push_back(v);
	}
	//排序去重 
	sort(alls.begin(), alls.end());
	alls.erase(unique(alls.begin(), alls.end()), alls.end()); 
	//离散化
	for(auto item: add){ //先对添加里的元素映射 赋值 
		x = item.first, c = item.second;
		a[find(x)] += c; //找到x的映射值 往原数组中加c 
	} 
	//求前缀和
	for(int i = 1; i <= alls.size(); i++){ //总的元素 
		s[i] = s[i-1] + a[i];
	} 
	for(auto item: query){
		u = item.first, v = item.second;
		cout<<s[find(v)] - s[find(u)-1]<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值