数据预处理—离散化

离散化,把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。

通俗的说,离散化是在不改变数据相对大小的条件下,对数据进行相应的缩小。

举个栗子:

四个数:1,999999,345,34

离散化完后为:1,4,3,2

也就是说对于给的数,我们不需要知道他的值具体是多少,只需要知道他们之间的相对大小。

这里介绍离散化的两种方法:

一、

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int t[N],a[N],n;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		t[i]=a[i];
	}
	sort(t+1,t+1+n);
	int m=unique(t+1,t+1+n)-(t+1);
	for(int i=1;i<=n;i++)
	a[i]=lower_bound(t+1,t+m+1,a[i])-t;
}

unique函数是C++自带的函数,对一个数组中的元素去重,在后面减去数组的首地址即得去重后的元素个数。

二、

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10; 
struct node{
	int v,id;
	bool operator < (const node a)const{
	   return v<a.v;
	}
}a[N]; 
int n,rank[N];
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i].v);
		a[i].id=i;
	}
	sort(a+1,a+1+n);
	for(int i=1;i<=n;i++){
		rank[a[i].id]=i;
	}
}

这个方法不能用于有重复元素的例子中。

猜你喜欢

转载自blog.csdn.net/curry___/article/details/83115690