离散化

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 1e4 + 9;

int n ;
struct node{
    int data;    // 数值
    int rank;    // 排名
    int idx;     //  下标
}a[N];

// 排序数值
bool cmp1(node &x, node &y){return x.data < y. data;}
//按编号排序回去
bool cmp2(node &x, node &y){return x.idx < y.idx;}

int main(){
    cin>>n;
    
      //给每个数据编号
    for(int i = 1; i <= n; i++)  cin>>a[i].data, a[i].idx = i;
    sort(a+1, a+1+n, cmp1);  // 按大小排序
    // 排序好的数值给一个大小排序
    for(int i = 1.; i <= n; i++) printf("%d ",a[i].data), a[i].rank = i; 
    printf("\n");
    sort(a+1, a+1+n, cmp2);  //排序回去
    for(int i = 1; i <= n; i++) printf("%d ",a[i].rank);
    
    return 0;
}

```

```
vector<int> alls; // 存储所有待离散化的值
sort(alls.begin(), alls.end()); // 将所有值排序
alls.erase(unique(alls.begin(), alls.end()), alls.end());  // 去掉重复元素

// 二分求出x对应的离散化的值
int find(int x) // 找到第一个大于等于x的位置
{
    int l = 0, r = alls.size() - 1;
    while (l < r){
        int mid = l + r >> 1;
        if (alls[mid] >= x) r = mid;
        else l = mid + 1;
    }
    return r + 1; // 映射到1, 2, ...n
}
```
posted @ 2021-02-21 22:59  Carrot_Rui  阅读(42)  评论(0)    收藏  举报