一、用vector进行离散化,把a数组内的数离散之后重新存储。
#include <bits/stdc++.h>
using namespace std;
int a[] = {0,34,5,28,20,30,33,76,12};
vector<int> v;
int main(){
for(int i=1; i<=7; i++) v.push_back(a[i]); //把所有数字放进vector
sort(v.begin(), v.end()); //排序
v.erase(unique(v.begin(),v.end()),v.end()); //unique去重
for(int i=1; i<=7; i++) a[i]=lower_bound(v.begin(), v.end(),a[i])-v.begin()+1; //离散化编号
for(int i=1; i<=7; i++) cout<<a[i]<<' '; //输出
}
update at 2022.7.23
如果把离散化封装成struct会更加方便使用,代码如下:
#include<bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define int long long
struct Disc {
static const int maxn = 5e5 + 5; //这是离散数组大小,有多少个不同的数,它就要多大
int p, b[maxn];
void init(int *a, int n) {
FOR(i, 1, n) b[i] = a[i];
sort(b + 1, b + n + 1);
p = unique(b + 1, b + n + 1) - (b + 1);
}
int find(int x){ //找x的位置,如果找不到,找偏大的
return lower_bound(b + 1, b + p + 1, x) - b;
}
int find2(int x){ //找x的位置,如果找不到,找偏小的
return upper_bound(b + 1, b + p + 1, x) - b - 1;
}
}di;
inline void solve(){
int a[] = {0,10,3,6,1,7}; //注意数组要从1位置开始
di.init(a,5);
cout<<di.find(3)<<' '<<di.find2(3)<<'\n'; //找3,能准确找到在2号位
cout<<di.find(5)<<' '<<di.find2(5)<<'\n'; //找5,发现没有,向上或者向下找
/* 输出:
2 2
3 2
*/
}
signed main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T=1; while(T--) solve();
}