Acwing 802.区间和 离散化详解

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
const int N = 3e5 + 10;
vector<int> position;
vector<PII> add,query;
int a[N];

int find(int x)
{
    int l = 0, r = position.size() - 1;
    while(l < r)
    {
        int mid = l + r >> 1;
        if(position[mid] >= x) r = mid;
        else l = mid + 1;
    }
    return r + 1;//hope to start with 1 
}

int main()
{
    int n, m;                           
    cin >> n >> m;
    for(int i = 0; i < n; i ++)
    {
        int x, c;
        cin >> x >> c;
        add.push_back({x,c});
        position.push_back(x);
    }
    for(int i = 0; i < m; i ++)
    {
        int l, r;
        cin >> l >> r;
        position.push_back(l);
        position.push_back(r);
        query.push_back({l,r});//因为询问和数字必须一起离散化收束才行 不然找不到收束后的位置
    }
    //离散化收束必要操作
    sort(position.begin(),position.end());
    position.erase(unique(position.begin(),position.end()),position.end());
    //
    for(auto it : add)//找到 add对中 要add的位置在已经收束完的离散集合里的位置 (有序的
    {//然后对号入座到a数组里 这个集合是已经处理好的元素
        int hash_position = find(it.first);// 5  8  90000  899990099
        a[hash_position] += it.second;     // 1  2  5      6
    }
    a[0] = 0;
    for(int i = 1;i <= position.size();i++) a[i] += a[i - 1];//浅醉和
    
    for(auto it : query)
    {
        int hash_position_l = find(it.first);//找到离散化之前的询问 对应收束后的位置
        int hash_position_r = find(it.second);
        cout << a[hash_position_r] - a[hash_position_l - 1] << endl;
    }
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值