离散化思想

离散化,把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。
通俗的说,离散化是在不改变数据相对大小的条件下,对数据进行相应的缩小。例如:
原数据:1,999,100000,15;处理后:1,3,4,2;
原数据:{100,200},{20,50000},{1,400};
处理后:{3,4},{2,6},{1,5};

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//将node数组中的x和y坐标离散化,传入的值是其方向代表的最小值,一般都传入1
//按照x从小到大,相同的x按照y值从小到大排序
typedef struct node
{
	int x,y;
}node;
bool cmpx(node x,node y){
    if(x.x<y.x) return true;
    else if(x.x>y.x) return false;
    else{
        if(x.y<y.y) return true;
        else return false;
    }
}
//按照y值从小到大,相同的y按照x值从小到大排序
bool cmpy(node x,node y){
    if(x.y<y.y) return true;
    else if(x.y>y.y) return false;
    else{
        if(x.x<y.x) return true;
        else return false;
    }
}
void lisanhua(node a[],int n,int &maxx,int &maxy){
	int nowloc=0,lastloc=0;
	sort(a,a+n,cmpx);//按照x从小到大到y从小到大排序
    while(lastloc < n){
        nowloc = lastloc;
        while(lastloc < n && a[lastloc].x==a[nowloc].x) lastloc++;
        for(int i=nowloc;i<lastloc;i++) a[i].x=maxx;
        maxx++;
    }
    nowloc=0;lastloc=0;
    sort(a,a+n,cmpy);
    while(lastloc < n){
        nowloc = lastloc;
        while(lastloc < n && a[lastloc].y==a[nowloc].y) lastloc++;
        for(int i=nowloc;i<lastloc;i++) a[i].y=maxy;
        maxy++;
    }
    //如果传入(a,1,1)得到的x的范围为[1,maxx),y的范围为[1,maxy)
}
int main(){
	int n,maxx=1,maxy=1;
	node a[10];
	cin >> n;
	for(int i=0;i<n;i++) scanf("%d%d",&a[i].x,&a[i].y);
	lisanhua(a,n,maxx,maxy);
	for(int i=0;i<n;i++) cout << a[i].x << "  " << a[i].y << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

门豪杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值