X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。
例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重叠。
Input
第1行:1个数N,线段的数量(2 <= N <= 10000) 第2 - N + 1行:每行2个数,线段的起点和终点(-10^9 <= S,E <= 10^9)
Output
输出最多可以选择的线段数量。
Input示例
3 1 5 2 3 3 6
Output示例
2
按终点升序排列 直接遍历即可
注:题意让求的是共有多少条互相不重叠的线段,而不是有多少两两互不重叠的线段
#include <iostream> #include <algorithm> #include <cstring> #include <map> using namespace std; struct Why { int a; int b; }A[10005]; int cmp(Why x,Why y) { if(x.b!=y.b) return x.b<y.b; } int N,ans; int main() { ios::sync_with_stdio(false); cin>>N; for(int i=0;i<N;i++) cin>>A[i].a>>A[i].b; sort(A,A+N,cmp); int end=A[0].b,t=0; for(int i=1;i<N;i++) { if(A[i].a>=end&&t==0) { end=A[i].b; ans=2; t=1; } if(A[i].a>=end&&t==1) { ans++; end=A[i].b; } } cout<<ans<<endl; return 0; }