离散化处理

  • 定义:离散化,把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。(百度百科
  • 作用:使数据的值域变小,便于根据值域构造树状数组、线段树等结构。
  • 步骤:输入,排序,去重,索引。
  • 注意:离散化仅适用于只关注元素之间的大小关系而不关注元素本身的值
  • 参考代码:
//离散化处理
//功能:将a数组中的数离散化到X数组,使值域变小
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100005;

int a[maxn],X[maxn],mapp[maxn];
int xcnt=0;

//查找值key在离散化后的数组的位置
int binX(int key,int n)
{
    //pos范围:0到n-1
    int pos = lower_bound(X,X+n,key)-X;
    return pos == n ? -1:pos;
}

int main()
{
    int n;
    scanf("%d",&n);
    for(int i = 0; i < n; ++i)
    {
        scanf("%d",&a[i]);
        X[xcnt++]=a[i];
    }
    sort(X,X+xcnt);
    xcnt = unique(X,X+xcnt)-X;
    //可选操作:将离散化前的位置与离散化后的位置映射起来
    //X[mapp[i]] = a[i]
    for(int i = 0; i < n; ++i)
        mapp[i]=binX(a[i],xcnt);
    return 0;
}
  • 如果需要考虑元素本身稍作变化的信息(比如加减k),可以将变化前后的值均离散化,再用多个数组或用结构体保存每个元素不同变化时的映射值.
  • 参考代码:
/**
离散化处理
功能:将a数组中的数以及其加k和减k的值离散化到X数组,使值域变小
     用mapp数组记录对应位置元素以及其加k减k的映射关系
**/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100005;

int a[maxn],X[maxn*3];
struct Node
{
    int key,l,r;
}mapp[maxn];
int xcnt=0;

//查找值key在离散化后的数组的位置
int binX(int key,int n)
{
    //pos范围:0到n-1
    int pos = lower_bound(X,X+n,key)-X;
    return pos == n ? -1:pos;
}

int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    for(int i = 0; i < n; ++i)
    {
        scanf("%d",&a[i]);
        X[xcnt++]=a[i];
        X[xcnt++]=a[i]-k;
        X[xcnt++]=a[i]+k;
    }
    sort(X,X+xcnt);
    xcnt = unique(X,X+xcnt)-X;
    //可选操作:将离散化前的位置与离散化后的位置映射起来
    //X[mapp[i].key] = a[i]
    //X[mapp[i].l] = a[i]-k
    //X[mapp[i].r] = a[i]+k
    for(int i = 0; i < n; ++i)
    {
        mapp[i].key=binX(a[i],xcnt);
        mapp[i].l=binX(a[i]-k,xcnt);
        mapp[i].r=binX(a[i]+k,xcnt);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值