ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

离散化

2020-03-01 10:52:34  阅读:247  来源: 互联网

标签:cor int back 离散 坐标 push include


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

标签:cor,int,back,离散,坐标,push,include
来源: https://www.cnblogs.com/WalterJ726/p/12388613.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有