有些数据本身很大, 自身无法作为数组的下标保存对应的属性。
如果这时只是需要这堆数据的相对属性, 那么可以对其进行离散化处理!
离散化:当数据只与它们之间的相对大小有关,而与具体是多少无关时,可以进行离散化。
例如
9 1 0 5 4 与 5 2 1 4 3 的逆序对个数相同。
设有4个数:
1234567、123456789、12345678、123456
排序:123456<1234567<12345678<123456789
=> 1 < 2 < 3 < 4
那么这4个数可以表示成:2、4、3、1
使用STL算法离散化:
思路:先排序,再删除重复元素,然后就是索引元素离散化后对应的值。
假定待离散化的序列为a[n],b[n]是序列a[n]的一个副本,则对应以上三步为:
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <algorithm> using namespace std; #define MAX 1000000 int a[MAX],b[MAX]; int main() { int m; while(~scanf("%d",&m)) { for(int i=0; i<m; i++) { scanf("%d",&a[i]); b[i]=a[i]; //b为a 的一个副本; } sort(a,a+m); int cnt=unique(a,a+m)-a; //离散化后的长度 for(int i=0; i<m; i++) printf("%d ",lower_bound(a,a+cnt,b[i])-a+1); //b[i]离散化后对应的值 printf("\n"); } } /* input: 5 9 3 1 6 11 output: 4 2 1 3 5 */
对于第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离散化大大减少了代码量且结构相当清晰。