区间和——离散化

使用一些现代C++的特性(如自动类型推导、范围循环、结构化绑定等)来进行简化和优化。

#include<bits/stdc++.h>
#define debug(a) cout << #a << "=" << a << endl;
#define endl "\n"
#define X first
#define Y second
const int N = 4e5 + 10;
using namespace std;

int n, m;
int a[N], b[N]; // 插入的值,前缀和的值
vector<int> alls; // 保存操作的所有原坐标
vector<pair<int, int>> add, query; // 存储插入和询问操作的数据

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 l;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        int x, c;
        cin >> x >> c;
        alls.push_back(x);
        add.emplace_back(x, c);
    }
    for (int i = 0; i < m; ++i) {
        int l, r;
        cin >> l >> r;
        query.emplace_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());

    // 执行前 n 次插入操作
    for (const auto& [x, c] : add) {
        a[find(x)] += c;
    }

    // 计算前缀和
    b[0] = a[0];
    for (size_t i = 1; i < alls.size(); ++i) {
        b[i] = b[i - 1] + a[i];
    }

    // 执行 m 次查询
    for (const auto& [l, r] : query) {
        int left = find(l);
        int right = find(r);
        cout << b[right] - (left > 0 ? b[left - 1] : 0) << endl;
    }

    return 0;
}

语法说明:

  1. 自动类型推导:使用 auto 关键字简化了类型的声明,特别是在循环和结构化绑定中。

  2. 结构化绑定:使用 const auto& [x, c]const auto& [l, r] 简化了 pair 的访问方式,使代码更简洁。

  3. emplace_back 替代 push_back:在向 vector 中添加元素时,使用 emplace_back 可以避免不必要的临时对象创建,效率更高。

  4. 优化了查询时的输出:通过 left > 0 ? b[left - 1] : 0 处理边界情况,简化了输出的计算。

  5. 提高输入输出效率ios::sync_with_stdio(false); cin.tie(0); 这一行代码用于加速输入输出操作,适用于需要频繁使用 cincout 的情况。

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值