1.区间和并
遍历方法易懂
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
vector<pii> jihe;
void hebing(vector<pii> &jihe)
{
vector<pii> res;
sort(jihe.begin(),jihe.end());
int st=-2e9,ed=-2e9;
for(int i=0;i<jihe.size();i++)
{
//没有交集
if(ed<jihe[i].first)
{
if(st!=-2e9)res.push_back({st,ed});//第一次跳过,以后每次进行
st=jihe[i].first;ed=jihe[i].second;//更新区间
}
//有交集
else
ed=max(ed,jihe[i].second);//更新区间
}
if(st!=-2e9)res.push_back({st,ed});//最后一个区间判断
jihe=res;
}
int main()
{
int n;
cin>>n;
for(int i =0;i<n ;i++)
{
int l,r;
scanf("%d%d",&l,&r);
jihe.push_back({l,r});
}
hebing(jihe);
//————————————————————————————————————————————————————
//------输出各个合并后的区间
//for(int i=0;i<jihe.size();i++)
//printf("%d %d\n",jihe[i].first,jihe[i].second);
//————————————————————————————————————————————————————
printf("%d\n",jihe.size());
return 0;
}
遍历方法使用auto
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
vector<pii> jihe;
void hebing(vector<pii> &A)
{
vector<pii> res;
sort(jihe.begin(),jihe.end());
int st=-2e9,ed=-2e9;
for(auto i:jihe)
{
if(ed<i.first)
{
if(st!=-2e9)res.push_back({st,ed});
st=i.first;ed=i.second;
}
else ed=max(ed,i.second);
}
if(st!=-2e9)res.push_back({st,ed});
jihe=res;
}
int main()
{
int n;
cin>>n;
for(int i =0;i<n ;i++)
{
int l,r;
scanf("%d%d",&l,&r);
jihe.push_back({l,r});
}
hebing(jihe);
//————————————————————————————————————————————————————
//------输出各个合并后的区间
//for(int i=0;i<jihe.size();i++)
//printf("%d %d\n",jihe[i].first,jihe[i].second);
//————————————————————————————————————————————————————
printf("%d\n",jihe.size());
return 0;
}