离散化及前缀和
离散化和前缀和算法,离散化是特殊的一种哈希
#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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署