ac802 区间和

注意 >> 的运算顺序在加减之后
// 找到所有要查询的和插入的位置,把这些位置去重排序,然后把他们映射为一个新的数组,这个数组的值就是哪些位置上有的值然后再用前缀和问题

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

    const int N = 300010;//
    int n, m;
    int a[N];//坐标插入的值
    int s[N];//a数组的前缀和
    vector<int> alls;//所有查询和和插入的坐标
    vector<pair<int, int>> add, query;//插入和询问的数据
    // 第一步 add 记录那个位置增加了多少, 然后alls记录被增加过的数字
    //第二步  query记录查询的左右 并且把这个左右都插入alls
    //第三步  给alls排序并且去重 
    //第四步  用find函数找到 add里面每一项的first 然后a数组记录,a数组的排放顺序是alls里面的顺序,个数也是alls的个数
    //第五步  用s数组算出a数组的前缀和  范围是alls的长度, 这里寻找也是用映射关系
    int find(int x) {
        int l = 0, r = alls.size() - 1;
        while (l < r) {
            int m = ((r - l )>> 1) + l;
            if (alls[m] >= x) r = m;
            else l = m + 1;
        }
        return r + 1;
    }
    int main() {
        scanf("%d %d", &n, &m);
        for( int i = 0; i < n; i++) {
            int x, c;
            scanf("%d %d", &x, &c);
            add.push_back({x,c});
            alls.push_back(x);
        }
        for( int i = 0; i < m; i++) {
            int l, r;
            scanf("%d %d", &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);//找到item.first在adds数组中第几位
            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);
            int r = find(item.second);
            printf("%d\n", s[r] - s[l-1]);
        }
    }
posted @ 2022-08-31 21:41  天然气之子  阅读(25)  评论(0编辑  收藏  举报