离散化

在一些问题上经常会出现一段很长的数轴,上面只有少数的几个点,同时我们只关注这些点的大小关系而不关注点本身的数值
这时离散化就很有帮助
离散化分两类
1:同时关注数值和数值出现的位置
这种离散化类似于排序pair,first优先,second其次

struct node
{
	int x, id;
}s[1010];
int r[1010];
bool cmp(node a, node b){
	return a.x < b.x;
}
int main()
{
	int n;
	cin >> n;
	for(int i = 1; i <= n; i++){
		cin >> s[i].x;
		s[i].id = i;
	}	
	sort(s+1,s+1+n,cmp);
	for(int i = 1; i <= n; i++){
		r[s[i].id] = i;
	}
	for(int i = 1; i <= n; i++){
		cout << r[i] << " ";
	}
	return 0;
}
/*
3
1 2 1
1 3 2
*/

2:只关注数值大小关系
这种离散化相同的数值会赋给相同的权值

int lsh[MAXN] , cnt , num[MAXN] , n;
for(int i=1; i<=n; i++) {
	scanf("%d",&num[i]);
	lsh[i] = num[i];	
}
sort(lsh+1 , lsh+n+1);
cnt = unique(lsh+1 , lsh+n+1) - lsh - 1;
for(int i=1; i<=n; i++)
	num[i] = lower_bound(lsh+1 , lsh+cnt+1 , num[i]) - lsh;
/*
3
1 2 1
1 2 1
*/
posted @ 2020-06-15 13:42  naymi  阅读(35)  评论(0)    收藏  举报