离散化及例题

离散化
当题目中设计的数据范围很大,但是我们用到的范围很小的时候,我们可以把所有用到的变量映射到较小的一个区域里面去.

保序

用排序+判重+二分

区间和

添加链接描述

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<int, int> PII;

const int N = 300010;

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

vector<int> alls;
vector<PII> add, query;

int find(int 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;
}

int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i ++ )
    {
        int x, c;
        cin >> x >> c;
        add.push_back({x, c});

        alls.push_back(x);
    }

    for (int i = 0; i < m; i ++ )
    {
        int l, r;
        cin >> l >> r;
        query.push_back({l, r});

        alls.push_back(l);
        alls.push_back(r);
    }

    // 去重
    sort(alls.begin(), alls.end());
    alls.erase(unique(alls.begin(), alls.end()), alls.end());

    // 处理插入
    for (auto item : add)
    {
        int x = find(item.first);
        a[x] += item.second;
    }

    // 预处理前缀和
    for (int i = 1; i <= alls.size(); i ++ ) s[i] = s[i - 1] + a[i];

    // 处理询问
    for (auto item : query)
    {
        int l = find(item.first), r = find(item.second);
        cout << s[r] - s[l - 1] << endl;
    }

    return 0;
}

103. 电影

添加链接描述

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 600010;

int n,m;
int a[N],b[N],c[N];

vector<int>alls,add;

int find(int 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;
}


int main()
{
    cin>>n;
    while (n -- )
    {
        int a;
        cin>>a;
        alls.push_back(a);
        add.push_back(a);
    }
    
    cin>>m;
    for(int i=0;i<m;i++)
    {
        cin>>b[i];
        alls.push_back(b[i]);
    }
    
    for(int i=0;i<m;i++)
    {
        cin>>c[i];
        alls.push_back(c[i]);
    }
    
    sort(alls.begin(),alls.end());
    alls.erase(unique(alls.begin(),alls.end()),alls.end());
    
    for(auto i:add)a[find(i)]++;
    
    int res=0,Like=0,like=0;
    for(int i=0;i<m;i++)
    {
        int L=a[find(b[i])],l=a[find(c[i])];
        if(Like<L)Like=L,like=l,res=i;
        else if (Like==L&&like<l)like=l,res=i;
    }
    cout<<res+1<<endl;
    return 0;
}

//把科学家会的语言和电影的语音的字幕全部离散化

不要求保序

法一

可以用map,每次去map里面查询一下这个值存不存在,如果存在就返回他的存在对应的值
如果不存在的话就给他对应的另一个值

哈希表

操作和map一样

  • 18
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值