你没看错,这道题就是水博客的。
本题有权限……
题目要求给出n条线段(Li,Ri),要求选出最多的线段,保证任意两条线段不会相交。
贪心的思路,假设目前求出一个值lst,表示最后一条线段的R值,然后对于一条新入的线段,如果lst<=L,说明可以容下,那就把这道线段加入答案中,更新lst,但如果不行,那怎么办?仔细思考后发现依旧贪心思路,把当前答案中最后一条线段剔除,然后加入这条线段,这样可以挪出更多的空间给接下来的牛。
复杂度
时间:O(n*logn)(别忘记排序); 空间:O(n)
代码
#include<cstdio> #include<algorithm> using namespace std; struct data{ int x,y; bool operator < (const data b)const{ return x<b.x||(x==b.x&&y<b.y); } }a[50005]; int n,ans,lst; inline void readi(int &x){ x=0; char ch=getchar(); while ('0'>ch||ch>'9') ch=getchar(); while ('0'<=ch&&ch<='9') {x=x*10+ch-'0'; ch=getchar();} } int main() { freopen("glass.in","r",stdin); freopen("glass.out","w",stdout); readi(n); for (int i=1;i<=n;i++) {readi(a[i].x); readi(a[i].y);} ans=lst=0; sort(a+1,a+n+1); for (int i=1;i<=n;i++) if (lst<=a[i].x) {lst=a[i].y; ans++;} else if (a[i].y<lst) lst=a[i].y; printf("%d",ans); return 0; }