跳到正文

算法·理论

关于离散化中lower_bound和map时间复杂度的讨论

fly_autumn约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年10月11日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

这是本蒟蒻第一次写这种时间复杂度讨论类型的文章,如有不严谨之处还请各位大佬予以指正,谢谢。

本蒟蒻在一周以前学了离散化以后,看到网络上主要有两种写法,一种是使用lower_bound的,另一种是使用map的,出于好奇想要对这两种方法的时间复杂度优劣进行一个比较。

下面以火烧赤壁一题展开分析。

题目跳转

这道题目的做法我就简略的讲讲,毕竟这是一篇论时间复杂度的专文。简而言之,就是记录n个区间(1<=n<=20000)每个区间是左闭右开的区间[a,b)(a,b均为int范围内的整数)。

毫无疑问,此题可以是一道标准的离散化板子题目,只需要用两个新的数组来替代a,b再进行排序即可,在此不赘述。

首先给出我的代码。

C++
#include<bits/stdc++.h>
using namespace std;
#define maxn 20005
int n;
int a[maxn],b[maxn];
int ctop,c[maxn*2];
int dtop,d[maxn*2];
bool f[maxn*2];
int x,y;
int main()
{
	scanf("%d",&n);
	for(int i = 1;i<=n;i++)
	{
		scanf("%d%d",&a[i],&b[i]);
		d[++dtop] = a[i];
		d[++dtop] = b[i];
	}
	sort(d+1,d+dtop+1);
	for(int i = 1;i<=dtop;i++)
	{
		if(d[i]!=d[i-1]||i==1)c[++ctop] = d[i];
	}
	for(int i = 1;i<=n;i++)
	{
		x = lower_bound(c+1,c+ctop+1,a[i])-c;//注意这里我用的是lower_bound
		y = lower_bound(c+1,c+ctop+1,b[i])-c;
		for(int j = x;j<y;j++)
		{
			f[j] = 1;
		}
	}
	int ans = 0;
	for(int i = 1;i<ctop;i++)
	{
		if(f[i]==1)ans+=c[i+1]-c[i];
	}
	printf("%d",ans);
	return 0;
}

以下是lower_bound的官方数据 接下来我将把这一段代码

C++
for(int i = 1;i<=dtop;i++)
{
	if(d[i]!=d[i-1]||i==1)c[++ctop] = d[i];
}
for(int i = 1;i<=n;i++)
{
	x = lower_bound(c+1,c+ctop+1,a[i])-c;
	y = lower_bound(c+1,c+ctop+1,b[i])-c;
	for(int j = x;j<y;j++)
	{
		f[j] = 1;
	}
}

修改为使用map的形式:

C++
for(int i = 1;i<=dtop;i++)
{
	if(d[i]!=d[i-1]||i==1)//here
	{
		c[++ctop] = d[i];
		Map[d[i]] = ctop;
	}
}
for(int i = 1;i<=n;i++)//这个循环体做了修改
{
	x = Map[a[i]];
	y = Map[b[i]];
	for(int j = x;j<y;j++)
	{
		f[j] = 1;
	}
}

洛谷评测下来的结果如下: 做成图表对二者进行对比就是这样:

测试点12345678910
lower_bound33ms4ms4ms7ms7ms10ms40ms5ms5ms4ms
map37ms4ms4ms8ms8ms11ms48ms5ms5ms4ms

由此我们可以得出:在对于相同规模的数据的时候,对于离散化这一步骤,lower_bound()实际上是要略快于map的。

原文