离散化操作

概念

先讲一下离散化操作的概念,举个例子会比较好说明.对于一组数组比如a[5]=6,9,5,5,4.进行离散化操作后就变成3,4,2,2,1.也就是说当需要用到的信息与数的绝对大小无关而与相对大小有关的时候就可以用上离散化操作.

实现

实现离散化操作需要用到两个函数 unique函数lowerbound函数.

unique函数

作用:去重

使用方法:unique(首地址,尾地址)

返回值:去重后的尾地址

原理:该函数实际上并没有去掉重复的元素而是把它们放在最后边

lower_bound函数

作用:在有序单调序列中查找值

使用方法:lower_bound(首地址,尾地址,需要查找的值)

返回值:返回第一个大于等于要找的值的地址,当不存在该值时返回序列中last位置(尾地址)

原理:二分查找

了解以上两个函数之后,只需要把需要离散化的数据另存起来,然后排序,再用unique去重,最后用lowerbound函数查找即可.

代码

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <string>
 8 #include <utility>
 9 #include <queue>
10 #include <stack>
11 #include <map>
12 #include <set> 
13 using namespace std;
14 const int INF=0x3f3f3f3f;
15 
16 const int MAX=1e5;
17 int a[MAX]; 
18 vector<int> v;
19 
20 int main()
21 {
22 //    freopen("in.txt","r",stdin);
23 //    freopen("out.txt","w",stdout);
24     int n;
25     cin>>n;
26     for(int i=0;i<n;i++)
27     {
28         cin>>a[i];
29         v.push_back(a[i]); //另存起来 
30     }
31     sort(v.begin(),v.end()); //排序 
32     vector<int>::iterator e=unique(v.begin(),v.end()); //去重 
33      for(int i=0;i<n;i++) //查找编序 
34     a[i]=lower_bound(v.begin(),e,a[i])-v.begin()+1;
35     for(int i=0;i<n;i++)
36     cout<<a[i]<<' ';
37     cout<<endl;
38     return 0;
39 }

猜你喜欢

转载自www.cnblogs.com/VBEL/p/10673164.html