Fork me on GitHub

离散化

https://blog.csdn.net/qq_44786250/article/details/100056975

unique返回尾坐标

解题思路

要算某个区间的和,直接使用前缀和来做就可以了

但是当这些区间的点中间很多个0的话,我们还是需要把他进行离散化

就是把原来的坐标映射到另外一个坐标当中去

  1. 首先我们把需要操作的坐标全部加入到alls数组当中
  2. 然后排序,把不必要的数字给删去
  3. 进行完之后,这个数组的数组下标对应的就是我们离散化之后的坐标。每次我们需要找坐标的时候直接用二分在这里面找就ok了
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 3e5 + 10;  // 加法有一份,查询有两份
typedef pair<int, int> PII;
vector<PII> add, query;
vector<int> cor;  // 离散化之后的坐标存储,alls
int a[maxn], s[maxn];  // 用于前缀和处理

int find(int x)
{
    int l = 0, r = cor.size() - 1;
    while(l < r)
    {
        int mid = l + r >> 1;
        if(cor[mid] >= x) r = mid;
        else l = mid + 1;
    }
    return r + 1; 
}

/*
vector<int>::iterator unique(vector<int> &a)
{
    int j = 0;
    for (int i = 0; i < a.size(); i ++ )
        if (!i || a[i] != a[i - 1])
            a[j ++ ] = a[i];
    // a[0] ~ a[j - 1] 所有a中不重复的数

    return a.begin() + j;
}
*/
int main()
{
    int n, m;
    int x, c;
    int l, r;
    cin >> n >> m;
    for(int i = 0; i < n; i ++) scanf("%d %d", &x, &c), add.push_back({x, c}), cor.push_back(x);
    for(int i = 0; i < m; i++) scanf("%d %d",&l, &r), cor.push_back(l), cor.push_back(r), query.push_back({l, r});
    
    sort(cor.begin(), cor.end());
    cor.erase(unique(cor.begin(), cor.end()), cor.end());  // unique返回尾坐标
    
    // 执行加的操作
    for(auto item : add)
    {
        int x = find(item.first);  // 找到映射之后的坐标
        a[x] += item.second;
    }
    
    // 处理前缀和操作
    for(int i = 1; i <= cor.size(); i++) s[i] = s[i - 1] + a[i];
    
    //处理查询
    for(auto item : query)
    {
        int l = find(item.first);  // 这里也需要找到坐标
        int r = find(item.second);
        int ans = s[r] - s[l - 1];
        cout << ans << endl;
    }
    return 0;
}

posted @ 2020-03-01 10:47  WalterJ726  阅读(121)  评论(0编辑  收藏  举报