利用离散化求区间和

拿AcWing 802. 区间和举例

输入样例:

3 3
1 2
3 6
7 5
1 3
4 6
7 8

输出样例:

8
0
5

 

从x的取值范围可见这类题与前缀和的应用是有区别的,

为了减少大量无用的操作,将其离散化

思路:

1.将所有出现的坐标(包括想求的边界)记下,因为这其中可能会有很大的数,导致求前缀和的时候经历许多对应值为零的坐标,尽可能在后续处理中避免这些坐标便是优化的方向

2.将1中记下的数进行排序,去重,并把这些坐标映射到1 ... n上,这并不难做到,比如坐标排序后有如下几个数: -9999, -11, 0, 7, 66666, 此时存放他们的容器size为5,我们将他们的位次作为他们的新名字,即 1,2,3,4,5 

3.同理前缀和 可见[练习](一二维 )前缀和 与 差分_☆迷茫狗子的秘密基地☆-CSDN博客

代码如下:

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

using namespace std;

const int N = 300010;

int a[N],s[N];
typedef pair<int, int> PII;

vector<int> alls;//需要做离散化处理的数
vector<PII> p, q;
int find(int x)
{
    int l=0, r=alls.size()-1;
    while (l < r)
    {
        int mid = (l + r) >> 1;
        //找到比x大的最小数
        if(alls[mid] >= x) r = mid;
        else l = mid+1;
    }
    return r+1;
}

vector<int>::iterator unique(vector<int> &a)
{
    int j = 0;
    for (int i = 0; i < a.size(); i ++ )
        if (!i || a[i] != a[i - 1])
            a[j ++ ] = a[i];

    return a.begin() + j;
}

int main()
{
    int n,m;
    int x,y;
    cin >> n >> m;
    for (int i = 0; i < n; i ++ )
    {
        scanf("%d%d", &x, &y);
        p.push_back({x, y});
        
        alls.push_back(x);
    }
    int l, r;
    for (int i = 0; i < m; i ++ )
    {
        scanf("%d%d", &l, &r);
        q.push_back({l, r});
        
        alls.push_back(l);
        alls.push_back(r);
    }
    
    sort(alls.begin(), alls.end());
    alls.erase(unique(alls),alls.end());//去重
    
    for (auto item : p)
    {
        int t = find(item.first);
        a[t] += item.second;
    }
    for (int i = 1; i <= alls.size(); i++) s[i] = s[i-1]+a[i];
    
    for(auto item : q)
    {
        int l = find(item.first);
        int r = find(item.second);
        cout << s[r]-s[l-1] << endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泥烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值