有些数据本身很大,自身无法作为数组的下标保存对应的属性。

如果这时只是需要这堆数据的相对属性, 那么可以对其进行离散化处理!

离散化:当数据只与它们之间的相对大小有关,而与具体是多少无关时,可以进行离散化。

使用STL算法离散化: 思路:先排序,再删除重复元素,然后就是索引元素离散化后对应的值。 假定待离散化的序列为a[n],b[n]是序列a[n]的一个副本,则对应以上三步为:

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;

int X[10] = {1234567, 1234567, 123456789,12345678, 123456};

int a[10] = {1234567, 1234567, 123456789, 12345678, 123456};

int main()     ////// n = 5
{
    sort(X, X+5);
    int size = unique(X, X+5)-X;
    for(int i = 0; i < 5; i++) a[i] = lower_bound(X, X+size, a[i])-X+1;
    
    for(int i = 0; i < 5; i++) printf("%d\n", a[i]);
    system("pause");
}
View Code

 

 

 

对于第3步,若离散化后序列为0, 1, 2, ..., size - 1则用lower_bound,从1, 2, 3, ..., size则用upper_bound,其中lower_bound返回第1个不小于b[i]的值的指针,而upper_bound返回第1个大于b[i]的值的指针,当然在这个题中也可以用lower_bound然后再加1得到与upper_bound相同结果,两者都是针对以排好序列。使用STL离散化大大减少了代码量且结构相当清晰。

posted on 2013-08-17 16:06  Buck Meister  阅读(917)  评论(0编辑  收藏  举报