常用技巧----离散化

这个技巧比较常用,当处理数据比较大,但是又不是很需要去关心数据的具体数值,而只需要去关心相对位置时会很有用(因为很多题目的数据范围会很大,但给的数据点却很少,或者这个数据范围是连续的时候)

比如 -2000000 200 600 -4000 600 2000000这种输入,要对其进行离散化,先对其进行排序,然后用unique进行去重,之后所对应的序号便是离散化后的数据。

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

using namespace std;

vector<int>id;

const int maxn = 10;

int main() {
    int n = 5, a[maxn], t[maxn];
    for(int i = 1;i <= n;i++) {
        scanf("%d", &a[i]);
        t[i] = a[i];//t是一个临时数组,用来得到离散化的映射关系
    }
    sort(t + 1, t + n + 1);//排序
    int m = unique(t + 1, t + 1 + n) - t - 1;
    for(int i = 1;i <=  n;i++)
    {
        a[i] = lower_bound(t + 1, t + 1 + m, a[i]) - t;
        // lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字。
        printf("%d ", a[i]); 
    }
}
发布了26 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/sad490/article/details/103792958
今日推荐