目 录CONTENT

文章目录

区间和

不争
2024-01-02 / 0 评论 / 0 点赞 / 9 阅读 / 1808 字

区间和

image-20220222161451971

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 300010;
typedef pair<int ,int> PII;

int n, m;
int a[N], s[N];// a[] 放离散化的位置 b[] 前缀和运算

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;
}

单纯分享下自己解题思路,我分享结束了,写的很一般多多包涵,如果有哪里我错误很愚蠢,很简陋的话,一定告诉我。希望我们共同进步。
谢谢观看!祝你们学业进步,身体健康,事业有成,家庭和睦。

0

评论区