模板代码——离散化

· · 算法·理论

//最标准且时间复杂度最短の写法,切忌要用lower_bound不要用STL,否则可能会被卡常
#include<bits/stdc++.h>
#define rep(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
const int N=1e5+5;

int t,n,a[N],b[N];
int main()
{
    cin>>t;
    while(t--)
    {
        int cnt=0;
        cin>>n;
        rep(i,1,n) cin>>a[i],b[++cnt]=a[i];
        //先排序再去重,勿写反,因为unique函数仅去重相邻的相同元素!!!
        sort(b+1,b+1+cnt);
        cnt=unique(b+1,b+1+cnt)-b-1;
        rep(i,1,n)
            a[i]=lower_bound(b+1,b+1+cnt,a[i])-b;
        rep(i,1,n) cout<<a[i]<<" ";
        cout<<endl;
    }
    return 0;
}