栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++区间和(离散化求解)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++区间和(离散化求解)

 

由题目可知x的数据范围为10的九次方,这个范围已经超过了我们数组可以开出的长度,并且,我们的n和m只有10的五次方,也就是需要操作的数最多只有3✖10的五次方个数,远远小于了x的数据范围,于是我们想到了离散化,也就是将所需要操作的数进行一个排序并且去重。是他们是有序的,也就是省去了中间是0的那些空间。

首先我们先定义一下数组和前提条件

#include
#include
#include
using namespace std;
typedef pair pii;
vector adds,quarry;//用来存储添加的x和c,以及m次的询问
vectoralls;//用来存储m次询问用到的数以及x
const int N=3e5+10;
int a[N],s[N];//前缀和数组

 接下来就是我们进行离散化的操作,分为两步,先排序,后去重。

//首先将操作的数装进alls,以及quarry,alls里面就是所有要操作的数,将他们进行排序以及去重。
while(m--)
{
int l,r;
alls.push_back(l);
alls.push_back(r);
quarry.push_back({l,r});
}
sort(alls.begin(),alls.end());//排序
alls.erase(unique(alls.begin(),alls.end()),alls.end());//去重

之后我们是要求区间和,这就要用到前缀和了,并且这是一维的前缀和也就是s[i]=s[i-1]+a[i]。

去重排序后sort里面的数就是我们需要操作的数,但是由于我们不知道要操作的数到底是在数组里面的哪一个位置,所以我们要进行一个查找,这里就选用简单的二分查找

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

这里我们return l+1是因为前缀和一般我们默认从数组的1号位置开始

接下来我们进行n次操作将x位置上的数加上c。

for(auto i:adds)
{
int x=find(i.first);
a[x]+=i.second;
}

接下来求前缀和

for(int i=1;i<=alls.size();i++)
{
s[i]=s[i-1]+a[i];
}

再接下来就是m次询问了

for(auto temp:quarry)
{
int l=find(temp.first), r=find(temp.second);
cout< 

总代码:

#include
#include
#include

using namespace std;
typedef pair PII;
const int N = 300010;
int a[N], s[N];

vectoralls;
vectoradds, qurry;
int n, m;
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 l + 1;
}
int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        int x, c;
        cin >> x >> c;
        adds.push_back({ x, c });
        alls.push_back(x);
    }
    while (m--)
    {
        int l, r;
        cin >> l >> r;
        alls.push_back(l);
        alls.push_back(r);
        qurry.push_back({ l,r });
    }
    //去重
    sort(alls.begin(), alls.end());
    alls.erase(unique(alls.begin(), alls.end()), alls.end());
    
    for (auto temp : adds)
    {
        int x = find(temp.first);
        a[x] += temp.second;
    }
    for (int i = 1; i <= alls.size(); i++)s[i] = s[i - 1] + a[i];
    for (auto temp : qurry)
    {
        int l=find(temp.first),r=find(temp.second);
        cout << s[r] - s[l - 1] << endl;
    }
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012524.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号