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

· · 算法·理论

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

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

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

题目跳转

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

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

首先给出我的代码。

#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的官方数据 接下来我将把这一段代码

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的形式:

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;
    }
}

洛谷评测下来的结果如下: 做成图表对二者进行对比就是这样: | 测试点 |1|2|3|4|5|6|7|8|9|10| |:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:| |lower_bound|33ms|4ms|4ms|7ms|7ms|10ms|40ms|5ms|5ms|4ms| |map|37ms|4ms|4ms|8ms|8ms|11ms|48ms|5ms|5ms|4ms|

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