离散化和区间合并
离散化
给出x和c在数轴上赋值,给l和r求区间和。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <climits>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n,m;
cin >> n >> m;
vector<pair<int,int>> X(n);
int L,R;
//用pair放x和c,然后哟个sort直接排序
for (int i = 0; i < n; i ++ ){
cin >> X[i].first >> X[i].second;
}
sort(X.begin(),X.end());//排序
//计算前缀和
vector<int> presum(n+1,0);
for (int i = 1; i <= n; i ++ ){
presum[i] = presum[i-1] + X[i-1].second;
}
for (int i = 0; i < m; i ++ ){
cin >> L>>R;
//二分查找边界并且输出
auto left = lower_bound(X.begin(),X.end(),make_pair(L,INT_MIN));//使用INT_MIN而不是0
auto right = upper_bound(X.begin(),X.end(),make_pair(R,INT_MAX));
auto l = left-X.begin();
auto r = right-X.begin()-1;
if(r>l){
cout << presum[r+1] - presum[l] << endl;
}else if(r==l){
cout << X[r].second << endl;
}else{
cout << 0<<endl;
}
}
return 0;
}
区间合并
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
int count = 0;
vector<pair<int,int>> g(n);
for (int i = 0; i < n; i ++ ){
cin >> g[i].first >> g[i].second;
}
//记录所有区间之后进行合并,从l到r进行扩展的方式,使用双指针试试看
int p=-1,q=-1;
int left = 0, right = 0;
int c = 0;
int edge = -1;
sort(g.begin(),g.end());
while(p<n-1&&edge < n-1){//左边边界和右边边界的判断,这里漏了酿成大错
p=edge+1;//结束,增加计数,移动指针。
q=p;
left = g[p].first;
right = g[q].second;
edge = q;
while(q<n-1){
q++;
if(right >= g[q].first){
right = max(g[q].second,right);//这里注意边界扩展的时候要取最大值而不是直接更新
edge = q;
}//如果右边大于等于下一个,则扩展边界
else{
break;//如果出现right比后面left小的应该直接跳出
}
}
c++;
}
cout<<c<<endl;
return 0;
} //怎么感觉这次漏洞百出