E - Third-Party Software - 2 Gym - 102215E (贪心)
Pavel is developing another game. To do that, he again needs functions available in a third-party library too famous to be called. There are mm functions numbered from 11to mm, and it is known that the ii-th version of the library contains functions from aiai to bibi inclusively.
The library is not free and Pavel needs all the functions. What minimal number of versions does he need to purchase to be able to use all the functions?
Input
The first line contains two integers nn and mm (1≤n≤200000,1≤m≤1091≤n≤200000,1≤m≤109) — the number of library versions and the number of functions.
Each of the next nn lines contains two integers aiai and bibi (1≤ai≤bi≤m1≤ai≤bi≤m) — the interval of function numbers available in the ii-th version.
Output
In the first line output «YES» or «NO», depending on if it's possible or not to purchase library versions to use all the functions.
In case of the positive answer output two more lines. In the second line output a single integer kk — the minimal number of library versions needed to be purchased. In the third line output kk distinct integers — the numbers of versions needed to be purchased.
If there are several possible answers, output any of them.
Examples
4 8 1 2 3 4 5 6 7 8
YES 4 1 2 3 4
4 8 1 5 2 7 3 4 6 8
YES 2 1 4
3 8 1 3 4 5 6 7
NO
题解:首先按照左端点从小到大排序,左端点相同按照右端点从大到小排序。然后贪心选取,将设当前能到达的最远点为now,我们需要在左端点<=now+1的线段中选取右端点最大的放进去,之后更新now。
其他不满足的情况特判即可。
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=200010; struct node { int l,r,id; }q[maxn]; int cmp(node a,node b)//按左端点从小到大,右端点从大到小排序 { if(a.l==b.l)return a.r>b.r; return a.l<b.l; } vector<int>ans; int main() { int n,m; cin>>n>>m; for(int i=1;i<=n;i++){ cin>>q[i].l>>q[i].r; q[i].id=i; } sort(q+1,q+1+n,cmp); if(q[1].l!=1)return cout<<"NO"<<endl,0; int now=q[1].r; ans.push_back(q[1].id);//首先将第一条放进去 for(int i=2;i<=n;){ if(q[i].l>now+1)return cout<<"NO"<<endl,0; else{ int temp=now,pos=q[i].id; while(i<=n&&q[i].l<=now+1){//在当前now可连接的取右端点最大值 if(q[i].r>temp){ temp=q[i].r; pos=q[i].id; } i++; } if(now==temp)continue;//防止不必要的放入 now=temp; ans.push_back(pos); } } if(now<m)return cout<<"NO"<<endl,0; cout<<"YES"<<endl; cout<<ans.size()<<endl; for(int i=0;i<ans.size();i++){ cout<<ans[i]<<" "; } cout<<endl; return 0; }