题解:P17178 Code Code Patch Crash
题解:P17178
解题思路
如果你做不出来,请注意:第 比赛时没看见直接痛失 50 分硬控我 3h。
设编号为
我们先判断有没有解。
当且仅当无论所有区间怎么排列,第
再来讨论有解的情况。
如果有解,就一定存在一种情况:有一个区间
特别的,如果
代码实现
解题代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int l,r;
}a[2000010];
int n,m;
bool cmp(node x,node y){
if(x.r==y.r)return x.l<y.l;
return x.r<y.r;
}
bool cmp2(node x,node y){
if(x.l==y.l)return x.r<y.r;
return x.l<y.l;
}
void solve(){
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>a[i].l>>a[i].r;
sort(a+1,a+n+1,cmp); // 按右端点排序
int mnr=0,mr=0x2000000;
bool fl=true;
for(int i=1;i<=n;i++){ // 如果所有区间都互相可达,无解
if(a[i].r>m)a[i].r=m;
mr=min(mr,a[i].r);
if(a[i].l>mr)fl=false;
}
if(fl){ // 判断是否无解
cout<<0<<endl;
return;
}
sort(a+1,a+n+1,cmp2); // 按左端点排序
mnr=a[1].l;
int ans=1;
for(int i=1;i<=n;i++){
if(mnr<a[i].l){ // 如果所有区间的交集=∅,直接输出 2
cout<<2<<endl;
return;
}
mnr=max(mnr,a[i].r);
}
cout<<3<<endl;
}
int main(){
ios::sync_with_stdio(false),cin.tie(0);
int t;
cin>>t;
while(t--)solve();
return 0;
}
时间复杂度分析
时间复杂度最高在于排序,时间复杂度为