acwing802.区间和——离散化

acwing802.区间和
在这里插入图片描述即:数据十分稀疏。
离散化就是一个映射的过程,将数据变得紧凑,便于处理。

模板如下

vector<int> alls; // 存储所有待离散化的值
sort(alls.begin(), alls.end()); // 将所有值排序
alls.erase(unique(alls.begin(), alls.end()), alls.end());   // 去掉重复元素

// 二分求出x对应的离散化的值
int find(int x) // 找到第一个大于等于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; // 映射到1, 2, ...n
}

作者:yxc
链接:https://www.acwing.com/blog/content/277/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

1.读入数据:注意要把查询区间的端点也读入alls中,不然查询的时候找不到这些点
2.排序去重:因为要进行二分查找所以排序,因为可能会存在重复的端点,但是有的端点是没有值的,这会影响接下来求前缀和,因此要去重。
3.处理添加:a数组是映射数组,下标就是原数组映射过来的值+1(为了便于处理前缀和),a数组的值就是对应原数组的值
4.处理询问:利用find函数找到询问端点在映射数组中的下标,然后再利用前缀和即可!

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

using namespace std;

typedef pair<int , int> PII;

const int N = 300010;

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

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

//二分查找大于等于x的数中最小的那个
int find(int x)
{
    int l = 0  , r = alls.size() - 1;
    while(l < r)
    {
        int mid = l + r >> 1;
        if(x <= alls[mid])  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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值