1.自然语言描述
考虑一系列已知的区间中有多少个交集。
将所有涉及到的区间进行排序(利用sort对pair类型数据排序时以first为准的特性)这样两个集合之间有三种关系:
设左端点first较小的区间为X,较大的为Y;
一、X.second<Y.first:即两个集合不相交。
二、X.second>=Y.first&&X.first<Y.first:即二者相交且交集为二者的真子集。
三、X.second>=Y.second:即X包含Y。
策略是,统计过程中,以st与ed作为当前度量区间的头和尾,让这个度量区间尽量长;即再第二、三种情况下,让ed尽量大,st尽量滞后,在第一种情况下,度量区间必须后移,st更新为下一个区间的左端点。
这样,与其说在统计交集,倒不如说是在统计整个区间集合中的间断区间,因为间断区间加一即为交集数量。
2.代码描述
题目:Acwing.803 区间合并题目链接
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
const int MAXN=1e5+10;
vector<PII> alls;
int n;
int main(void)
{
cin>>n;
for(int i=0;i<n;i++){
int l,r;
cin>>l>>r;
alls.push_back({l,r});
}
sort(alls.begin(),alls.end());
int st=-2e9,ed=-2e9,cnt=0;
for(auto it:alls){
int l=it.first,r=it.second;
if(ed<l){
if(st!=-2e9)//排除掉初始st未更新的情况
cnt++;
st=l,ed=r;//度量区间更新(情况一)
}else
ed=max(ed,r);//度量区间的右端点尽量大(情况二、三)
}
if(st!=-2e9)//此时还剩最后的区间,一并记入
cnt++;
cout<<cnt<<endl;
return 0;
}