一种基于 pb_ds 的更好写且常数更小的离散化方式

一般大家实现离散化都是 sort + lower_bound

但是这里也许有一种时间复杂度更优一点且更好写的实现,适合卡常时使用

我们需要使用 pb_ds 的hash表 ,不会的可以看我的 这篇文章

与正常离散化不同的是,我们使用 gp_hash_table 来代替离散化,同时还可以省去 去重 的步骤

由于哈希表单次操作的复杂度是 \(O(1)\) 的,所以总复杂度是 \(O(n \log n + n)\)

具体实现方式见代码

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>

using namespace std;
__gnu_pbds::gp_hash_table<int, int> hash_;
int tot_[1000100], tot,cnt_s;
int n, m;
int a[500100];
int b[500100];
bool cmp(int a, int b)
{
    return a < b;
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int ww = 1; ww <= n; ww++)
    {
        cin >> a[ww];
        tot_[++tot] = a[ww];
    }
    for (int ww = 1; ww <= m; ww++)
    {
        cin >> b[ww];
        tot_[++tot] = b[ww];
    }
    sort(tot_ + 1, tot_ + 1 + tot, cmp);//排序 O(n log n)
    for (int ww = 1; ww <= tot; ww++)//O(n)
    {
        if (hash_[tot_[ww]] == 0)//如果这个值没有出现过
        {
            cnt_s++;
            hash_[tot_[ww]] =cnt_s;//记录离散化后的值
        }
    }
    bool tag_2 = 1;
    for (int ww = 1; ww <= m; ww++)
    {
        bool tag_ = 1;
        cout<<hash_[b[ww]]<<" " ;
    }


    return 0;
}

但是这样实现也有缺点,就是会有 hash表 的带来的额外空间复杂度,使用时注意空间即可

posted @   sea-and-sky  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示