• ACWING_802_区间和


    假定有一个无限长的数轴,数轴上每个坐标上的数都是0。

    现在,我们首先进行 n 次操作,每次操作将某一位置x上的数加c。

    近下来,进行 m 次询问,每个询问包含两个整数l和r,你需要求出在区间[l, r]之间的所有数的和。

    输入格式

    第一行包含两个整数n和m。

    接下来 n 行,每行包含两个整数x和c。

    再接下里 m 行,每行包含两个整数l和r。

    输出格式

    共m行,每行输出一个询问中所求的区间内数字和。

    数据范围

    109x109−109≤x≤109,
    1n,m1051≤n,m≤105,
    109lr109−109≤l≤r≤109,
    10000c10000−10000≤c≤10000

    输入样例:

    3 3
    1 2
    3 6
    7 5
    1 3
    4 6
    7 8
    

    输出样例:

    8
    0
    5

    思路:这是一道可以用离散化来做的题目,题中要求我们对数轴上随机的一些位置家伙加上一些数,因为位置可能非常大,也可能是负数,所以直接用数组下标的表示方法是不合适的,所以我们考虑使用离散化的技巧;然后我们离散化之后
    需要通过给出的l,r算出l到r中数的和,因为数的总范围可能会到1e5,然后最多可能又1e5次查询,所以考虑到时间复杂度的情况我们想到用前缀和,在寻找映射过程中也使用到了二分。
    AC代码:
    #include <iostream>
    #include <cstdio>
    #include <map>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    typedef pair<int, int> PII;
    
    const int maxn = 3e5 + 5;
    int a[maxn], s[maxn];
    vector<PII> add, query;
    vector<int> alls;
    
    inline int find(int x) {
        int l = 0, r = alls.size() - 1;
        while(l < r) {
            int mid = l + r + 1 >> 1;
            if(alls[mid] <= x) l = mid;
            else r = mid - 1; 
        }
        
        return l;
    }
    
    int main(void) {
        register int n, m, x, c, le, ri;
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i ++) {
            scanf("%d%d", &x, &c);
            add.push_back({x, c});
            
            alls.push_back(x);
        }
        
        for(int i = 1; i <= m; i ++) {
            scanf("%d%d", &le, &ri);
            query.push_back({le, ri});
            alls.push_back(le);
            alls.push_back(ri);
        }
        
        sort(alls.begin(), alls.end());
        alls.erase(unique(alls.begin(), alls.end()), alls.end());
        
        for(int i = 0; i < n; i ++) {
            int tmp = find(add[i].first);
            a[tmp + 1] += add[i].second; 
        }
        
        for(int i = 1; i <= alls.size(); i ++) s[i] = s[i - 1] + a[i];
        
        for(int i = 0; i < m; i ++) {
            le = find(query[i].first) + 1;
            ri = find(query[i].second) + 1;
            printf("%d
    ", s[ri] - s[le - 1]);
        }
        
        
        
    
        return 0;
    }
  • 相关阅读:
    分享 | 自定义属于自己的U盘图标
    GIF工具 | 分享几个Gif相关工具
    XTU | 人工智能入门复习总结
    XTU | 物联网概论复习总结
    收纳箱2号 | 前端开发大全
    收纳箱1号 | GitHub Pages部署静态网页的一点私货
    博客 | 基于Travis CI实现Hexo在Github和Coding的同步自动化部署
    图床plus演示 | 图床及在线分享演示文稿工具
    css写实心正三角和倒三角
    React 多个className的写法
  • 原文地址:https://www.cnblogs.com/phaLQ/p/11107103.html
Copyright © 2020-2023  润新知