区间和(离散化)

 

#include<bits/stdc++.h>
using namespace std;

typedef pair<int, int> PII;

int n,m;
vector<int> alls;
vector<PII> add, query;     // 存储题目输入的数据
int a[300010] = {0};        // 存储离散化后的数组
int sumMap[300010] = {0};   // 存储离散化后的数组的前缀和

int reflect(int x)
{
    int L = 0,R = alls.size()-1; // R不是n-1,因为alls的大小最多能达到300000,而非n
    int mid = L + R >> 1;
    while(L < R)    // 这里必须是<,如果是≤则死循环
    {
        if(alls[mid] >= x) R = mid;
        else L = mid + 1;
        mid = L + R >> 1;
    }
    return R+1; //+1使得数组下标从1开始
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    
    cin>>n>>m;
    
    int x,c;
    for(int i=0;i<n;++i)
    {
        cin>>x>>c;
        alls.push_back(x);
        add.push_back({x,c});
    }
    
    int l, r;
    for(int i=0;i<m;++i)
    {
        cin>>l>>r;
        query.push_back({l, r});
        
        alls.push_back(l); // 将区间的首尾加入到alls中,方便之后二分查找计算前缀和
        alls.push_back(r);
    }
    
    
    // 要保证每个x有且仅有一个对应的映射值,因此需要消去重复的x,下面是公式
    sort(alls.begin(), alls.end());
    alls.erase(unique(alls.begin(), alls.end()), alls.end());
    
    
    for(auto it : add)
    {
        int x = reflect(it.first);
        a[x] += it.second;
    }
    
    for(int i=1;i<=alls.size();++i) // <=alls.size()而非<=n,原因同reflect()函数里的R
        sumMap[i] += sumMap[i-1] + a[i];
    
    for(auto it : query)
    {
        int l = reflect(it.first);
        int r = reflect(it.second);
        
        cout<<sumMap[r] - sumMap[l-1]<<'\n';
    }
    
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值