离散化及前缀和
离散化和前缀和算法,离散化是特殊的一种哈希
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 3e5+10;
typedef pair<int, int> PII;
int m,n;
int a[N],s[N];
vector<int> alls;
vector<PII> add,query;
//二分查找x离散化后的下标
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;
}
//因为后面要用到前缀和,所以这里下标从1开始
return r + 1;
}
int main()
{
cin>>n>>m;
//读入所有插入操作并把需要离散化的点加入到alls里
for(int i = 0; i < n; i ++ )
{
int x,c;cin>>x>>c;
add.push_back({x,c});
alls.push_back(x);
}
//读入所有询问操作并把需要离散化的点加入alls
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());
for(auto m : add)
{
int x = find(m.first);
a[x] += m.second;
}
//预处理前缀和
for(int i = 1; i <= alls.size(); i++ ) s[i] += s[i-1] + a[i];
//输出答案
for(auto m : query)
{
int l = find(m.first), r = find(m.second);
cout<<s[r]-s[l-1]<<endl;
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 工良出品 | 长文讲解 MCP 和案例实战
· 多年后再做Web开发,AI帮大忙
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· centos停服,迁移centos7.3系统到新搭建的openEuler
· 一天 Star 破万的开源项目「GitHub 热点速览」