学习笔记:离散化

本文介绍了一种离散化方法在处理区间和问题中的应用,通过将无限空间中的坐标范围限制在有限范围内,利用前缀和实现对大量数据的高效查询。博客详细讲解了如何离散化坐标,使用二分查找映射,并通过实例展示了在AcWing竞赛中的具体实现。
摘要由CSDN通过智能技术生成

离散化 是把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。通俗的说,离散化是在不改变数据相对大小的条件下,对数据进行相应的缩小。

看一个例子:
AcWing 802. 区间和

假定有一个无限长的数轴,数轴上每个坐标上的数都是0。

现在,我们首先进行 n 次操作,每次操作将某一位置x上的数加c。

接下来,进行 m 次询问,每个询问包含两个整数l和r,你需要求出在区间[l, r]之间的所有数的和。
(-1e9 <= x,l,r <= 1e9, 1 <= n,m <= 1e5, -1e4 <= c <= 1e4)

做法:
可以看出,我们不能简单的将坐标作为数组下标,因为坐标的范围很大,数组开不了这么大,但是我们发现尽管坐标的范围非常大,但是用到的坐标是有限个的,因为最多只有(m+n)次询问,就算每次询问都会用到一个不同的坐标,最多会有3e5个不同的坐标被用到,这个范围是可以接受的
所以做法就是 将坐标离散化,最后用前缀和处理一遍,输出答案

#include<cstdio>
#include<cmath>
#include<ctime>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<vector>
#define ll long long
#define ull unsigned long long
#define up_b upper_bound
#define low_b lower_bound
#define m_p make_pair
#define mem(a) memset(a,0,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define inf 0x3f3f3f3f
#define endl '\n'
#include<algorithm>
using namespace std;

inline ll read()
{
	ll x=0,f=1; char ch=getchar();
	while(ch<'0'||ch>'9')	{ if(ch=='-') f=-1; ch=getchar(); }
	while('0'<=ch&&ch<='9')	x=x*10+ch-'0', ch=getchar();
	return f*x;
}

const int maxn = 3e5+5;

int n,m;
int a[maxn],s[maxn];

vector<int> alls;//存放待离散化的坐标 
vector<pair<int,int> > add,query;//存放添加操作与询问操作 

int find(int x)//查找坐标x离散化后对应的数组下标 
{
	int l=-1,r=alls.size();
	while(l+1!=r)//二分查找 
	{
		int mid=l+r>>1;
		if(alls[mid]>=x)	r=mid;
		else	l=mid;
	}
	return r+1;//将x映射到1,2...n 
	// 如果 return r; 是映射到 0,1,2... 
}

int main()
{
	cin>>n>>m;
	//先将所有用到的坐标存进去 
	for(int i=0;i<n;i++)
	{
		int x,c;
		cin>>x>>c;
		
		alls.push_back(x);
		add.push_back(m_p(x,c));
	}
	for(int i=0;i<m;i++)
	{
		int l,r;
		cin>>l>>r;
		
		alls.push_back(l); alls.push_back(r);
		query.push_back(m_p(l,r));
	}
	
	// 排序 + 去重 
	sort(alls.begin(),alls.end());
	alls.erase(unique(alls.begin(),alls.end()),alls.end());
	
	//处理添加操作 
	for(int i=0;i<n;i++)
	{
		int pos=find(add[i].first);
		a[pos]+=add[i].second; 
	}
	
	//对数组a进行前缀和处理
	for(int i=1;i<=alls.size();i++)	s[i]=s[i-1]+a[i];
	
	//处理查询操作
	for(int i=0;i<m;i++)
	{
		int l=find(query[i].first), r=find(query[i].second);
		cout<<s[r]-s[l-1]<<endl;
	}
	return 0;
}

y总的离散化模版:

vector<int> alls; // 存储所有待离散化的值
sort(alls.begin(), alls.end()); // 将所有值排序
alls.erase(unique(alls.begin(), alls.end()), alls.end());   // 去掉重复元素

// 二分求出x对应的离散化的值
int find(int x) // 找到第一个大于等于x的位置
{
    int l = 0, r = alls.size() - 1;
    while (l < r)
    {
        int mid = l + r >> 1;
        if (alls[mid] >= x) r = mid;
        else l = mid + 1;
    }
    return r + 1; // 映射到1, 2, ...n
}

作者:yxc
来源:AcWing
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值