离散化算法

本文介绍了如何使用C++实现离散化算法,包括数据的离散化处理、前缀和数组的计算以及通过二分查找功能对查询进行高效处理。
摘要由CSDN通过智能技术生成

 离散化算法的思想是将一组连续的数据映射到一组离散的取值,通常是整数。它的主要目的是将连续的数据转换为离散的数据,以便进行统计、计数、排序等操作。

 

 C++代码实现:
 

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

const int N = 300000;
int n, m;
int a[N]; // 存储每个离散化后的值对应的增量
int s[N]; // 存储前缀和数组
vector<int> alls; // 存储所有需要离散化的值
vector<pair<int,int>> add, query; // 存储输入的add和query数组

// 二分查找函数,用于找到x在alls中的位置
int find(int x){
    int l = 0; // 左边界
    int r = alls.size() - 1; // 右边界
    while(l < r){
        int mid = l + r >> 1; // 计算中间位置
        if(alls[mid] >= x){ // 如果中间位置的值大于等于x
            r = mid; // 更新右边界
        }
        else{
            l = mid + 1; // 更新左边界
        }
    }
    return r + 1; // 返回x在alls中的位置
}

int main(){
    // 读取n和m的值
    cin >> n >> m;
    
    // 读取add数组的值
    for(int i = 0; i < n; i++){
        int x, c;
        cin >> x >> c;
        add.push_back({x, c}); // 将x和c作为一对加入add数组
        alls.push_back(x); // 将x加入alls数组
    }
    
    // 读取query数组的值
    for(int i = 0; i < m; i++){
        int l, r;
        cin >> l >> r;
        query.push_back({l, r}); // 将l和r作为一对加入query数组
        alls.push_back(l); // 将l加入alls数组
        alls.push_back(r); // 将r加入alls数组
    }
    
    // 对alls进行排序并去重
    sort(alls.begin(), alls.end()); // 对alls数组进行升序排序
    alls.erase(unique(alls.begin(), alls.end()), alls.end()); // 去除alls数组中的重复元素
    
    // 根据add数组更新a数组
    for(auto item : add){
        int x = find(item.first); // 找到item.first在alls中的位置
        a[x] += item.second; // 将item.second加到a[x]上
    }
    
    // 计算前缀和数组s
    for(int i = 1; i <= alls.size(); i++){
        s[i] = s[i - 1] + a[i]; // 计算前缀和
    }
    
    // 根据query数组输出结果
    for(auto item : query){
        int l = find(item.first); // 找到item.first在alls中的位置
        int r = find(item.second); // 找到item.second在alls中的位置
        cout << s[r] - s[l - 1] << endl; // 输出结果
    }
    
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值