一、离散化
主要思想:将稀疏的分散值一一映射到正数集:1、2、3……,使得它们可以通过正数集下标聚集起来,实现储存与计算。
例题:给出n个加操作,每次在数轴x的位置上加上数c,再查找m个区间范围(l,r)的和。
#include<iostream>
#include<vector>
#include<algorithm>
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)/2;
if(alls[mid]>=x) r=mid;
else l=mid+1;
}
return r+1;//返回的是映射后的下标,a数组从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());//去重
//进行加操作
for(auto item:add){
int x=find(item.first);//进行数轴点的映射
a[x]+=item.second;
}
//从1开始,判定条件取等于号
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;//利用前缀和公式输出范围和
}
return 0;
}
二、数组合并
主要思想:将小数组按左端点进行排序后,分情况讨论:
①下一个数组的右端点小于等于当前数组的右端点,即当前数组包含下一个数组,不需要合并。
②下一个数组的右端点大于当前数组的右端点,即当前数组和下一个数组有交叉,需要合并,合并后数组右端点为下一个数组右端点。
③下一个数组左端点大于当前数组右端点,即下一个数组都大于当前数组,当前数组已经是最大合并数组,进行答案储存,更换比较的基准数组。
例题:给出一系列数组,求合并后的数组个数。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,int> PII;
vector<PII> segs;
int n;
void merge(vector<PII> &segs){//合并数组
sort(segs.begin(),segs.end());//c++中数值对排序先比较第一个值,再比较第二个值
int st=-2e9,ed=-2e9;//基准数组的初始化,根据题目规模设极小值
vector<PII> res;//答案集合
for(auto seg:segs){
if(seg.first>ed){//第③种情况,记录答案并更新基准数组
if(st!=-2e9) res.push_back({st,ed});
st=seg.first;
ed=seg.second;
}
else ed=max(ed,seg.second);//第①、②种情况,更新基准数组右端点
}
if(st!=-2e9) res.push_back({st,ed});//判定不为空后储存最后一个数组
segs=res;
}
int main(){
cin>>n;
int l,r;
for(int i=0;i<n;i++){
cin>>l>>r;
segs.push_back({l,r});
}
merge(segs);
cout<<segs.size()<<endl;
return 0;
}