第一种:利用结构体实现离散化
这种方法的弊端是无法辨别重复元素
例如
1 2 2 3 3
离散化之后是
1 2 3 4 5
使用时应注意
#include <bits/stdc++.h>
using namespace std;
const int N=5e5+10;
int n;
int b[N];
struct node
{
int id,val;
bool operator <(const node& a)const
{
return val<a.val;
}
}arr[N];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
cin>>arr[i].val;
arr[i].id=i;
}
sort(arr+1,arr+n+1);
for(int i=1;i<=n;i++) b[arr[i].id]=i;
for(int i=1;i<=n;i++) cout<<b[i]<<" ";
cout<<endl;
} 第二种:利用STL中的unique()和 lower_bound() 函数实现
unique函数:
去重函数
使用方法:unique (首地址,尾地址);
功能:去除相邻的重复元素(只保留一个),并把重复的元素放在最后;
unique 是返回去重后的尾地址;
lower_bound() 函数,在前闭后开区间进行二分查找
lower_bound() 是返回>=val 的位置,当所有元素都小于val,返回last位置;
使用方法:lower_bound(首地址,尾地址,待查找元素val);
upper_bound() 函数,在前闭后开区间进行二分查找
upper_bound() 函数是返回>val 的位置,其余与lower_bound()相同
#include <bits/stdc++.h>
using namespace std;
const int N=5e5+10;
int n;
int arr[N];
int b[N];
void print()
{
for(int i=1;i<=n;i++)
printf("%d ",arr[i]);
puts("");
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&arr[i]);
b[i]=arr[i];
}
sort(b+1,b+n+1);
int m=unique(b+1,b+n+1)-b-1;
for(int i=1;i<=n;i++)
arr[i]=lower_bound(b+1,b+m,arr[i])-b;
print();
return 0;
}


京公网安备 11010502036488号