y总模板之区间和(离散化问题)

#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;

typedef pair<int, int> PII;
int n, m, l, r, x, c;
int a[N], s[N];
//所有输入的数据全部成对出现,使用二元组保存数据;
vector<PII> add, query;
vector<int> alls;

//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() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n >> m;
	while(n--){
		cin >> x >> c;
		add.push_back({x, c});
		alls.push_back(x);
	}

	while(m--){
		cin >> l >> r;
		query.push_back({l, r});
		alls.push_back(l); alls.push_back(r);
	}
//排序、去除区间重复的数;
	sort(alls.begin(), alls.end());
	alls.erase(unique(alls.begin(), alls.end()), alls.end());
	for (auto item : add) {
		int new_x = find(item.first);
		a[new_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] << '\n';
	}

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值