0
点赞
收藏
分享

微信扫一扫

【C++】 Day 11 零散化 AcWing 802. 区间和 (全注释)

萨科潘 2022-02-06 阅读 84

传送门

1、题目

2、思路

3、AC代码


C++还没入门,代码看了十多遍 ,补了点语法,终于ac了!!

1、题目

      链接:https://www.acwing.com/activity/content/problem/content/836/

2、思路

离散化,把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。

通俗的说,离散化是在不改变数据相对大小的条件下,对数据进行相应的缩小。例如:

原数据:1,999,100000,15;处理后:1,3,4,2;

原数据:{100,200},{20,50000},{1,400};

处理后:{3,4},{2,6},{1,5}; ----百度

如图

 

算法应用:①排序②去除重复数字 ③相应处理

3、AC代码

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

typedef pair<int, int> PII;

const int N = 300010;

int n, m;
int a[N], s[N];

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; //  因为要求前缀和,故下标从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());//去除重复元素
   // 1)erase( pos, n); 删除从pos开始的n个字符,例如erase( 0, 1),
   // 删除0位置的一个字符,即删除第一个字符
    //(2)erase( position); 
    //删除position处的一个字符(position是个string类型的迭代器)
    //(3)erase(first,last);删除从first到last之间的字符,
   // (first和last都是迭代器)last 不能是x.end()
    //unique 使用 必须要先过一遍sort排序。再者,unique函数返的返回值是
    //一个迭代器,它指向的是去重后容器中不重复序列的最后一个元素的
    //下一个元素。所以如果 想要得到不重复元素的个数就需要用返回值-开始地址。
    for ( auto item : add) { //先对添加里的元素映射 赋值 
        int x = find(item.first);//找到x的映射值 往原数组中加c 
        a[x] += item.second; // 处理插入
    }
    //for(auto a:b)中b为一个容器,效果是利用a遍历并获得b容器中的每一个值,
    //但是a无法影响到b容器中的元素。
    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;
    }//每个元素都对应一组{first, first}键值对(pair),
    //键值对中的第一个成员称为first,第二个成员称为second.
    return 0;
}
举报

相关推荐

0 条评论