基础算法:离散化

基础算法:离散化

题目描述

在这里插入图片描述

参考代码

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

typedef pair<int, int> PII;

const int N = 300010;
int n, m;

int a[N], s[N];                 // 离散化后的数组,前缀和数组
vector<int> alls;               // 所有需要离散化的坐标数组

vector<PII> add, query;         // 用于存储输入和查询

int find(int x)
{   
    // 在alls数组中二分法查找目标元素坐标(映射),alls存储的原始坐标,已去重,单调
    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;       // 映射后的坐标从1开始索引,便于利用前缀和方法
}

int main()
{
    // 输入部分
    cin >> n >> m;      // n行输入, m行查询
    for (int i = 0; i < n; i++)
    {
        int x, c;
        cin >> x >> c;
        add.push_back({x, c});

        alls.push_back(x);
    }

    for (int i = 0; i < m; i++)
    {
        int l, r;
        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 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)
    {   
        // 将询问的坐标也离散化
        int l = find(item.first), r = find(item.second);
        cout << s[r] - s[l - 1] << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值