离散化[模板]

首先先看一下离散化是什么。
举个例子,你有些很大的数,现在要你对他们进行一些处理(比如hash一下什么的),当只需要它们的相对大小关系时,可以进行离散化来节约空间复杂度。
原数:

45451212 3212313215321 548468354545122545 78461

离散化后:

2 3 4 1

相对大小是不变的,排序一下也是可以的。
那么怎么实现离散化呢?
看代码吧

#include<iostream>
#include<cstdio>
#include<algorithm>//要用到几个复杂的函数,大家可以查一下
using namespace std;
int a[1005],b[1005];//a为原数,b为离散化后的数 
int n;
int cnt;
int main() 
{  
    cin>>n; 
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        b[++cnt]=a[i];//先存进b去再处理
    }
    sort(b+1,b+1+cnt);//排序
    cnt=unique(b+1,b+1+cnt)-b-1;//去重(离散化是去重的)
    for(int i=1;i<=n;i++)
        cout<<lower_bound(b+1,b+1+cnt,a[i])-b<<endl;
}

猜你喜欢

转载自blog.csdn.net/floatiy/article/details/79366003