跳到正文

算法·理论

模板代码——离散化

wbqhasvcf约 1 分钟
原文
文章信息与版本

文章信息

发布
2026年10月14日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 1 分钟

版本

  1. v1当前
C++
//最标准且时间复杂度最短の写法,切忌要用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;
}
原文