There are N line segments on the X-axis, and each line segment has a start point S and an end point E. The maximum number of non-overlapping line segments that can be selected. (Note: The starting point or the ending point overlaps, and it is not counted as overlapping).
For example: [1 5][2 3][3 6], you can choose [2 3][3 6], these two line segments do not overlap each other.
Input
Line 1: 1 number N, number of line segments (2 <= N <= 10000) Line 2 - N + 1: 2 numbers per line, start and end points of line segments (-10^9 <= S,E <= 10^9)
Output
Output the maximum number of line segments that can be selected.
Input example
3 1 5 2 3 3 6
Output example
2
Sort in ascending order by end point and traverse directly
Note: The purpose of the question is to ask how many non-overlapping line segments there are, rather than how many pairs of non-overlapping line segments.
#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,years; intmain() { 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; years=2; t=1; } if(A[i].a>=end&&t==1) { years++; end=A[i].b; } } cout<<ans<<endl; return 0; }