X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。
例如:151523233636,可以选23233636,这2条线段互不重叠。
Input
第1行:1个数N,线段的数量(2 <= N <= 10000)
第2 - N + 1行:每行2个数,线段的起点和终点(-10^9 <= S,E <= 10^9)
Output
输出最多可以选择的线段数量。
Sample Input
3 1 5 2 3 3 6
Sample Output
2
代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
int s,e;
}a[10010];
bool cmp(node x,node y)
{
if(x.s !=y.s )//起点若不相等,从小到大排
return x.s<y.s ;
else
return x.e <y.e; //起点相等时,终点从小到大排
}
int N,i,j;
int main()
{
cin>>N;
for(i=0;i<N;i++)
cin>>a[i].s >>a[i].e ;
sort(a,a+N,cmp);
int sum=0;
for(i=0;i<N;i++)
{
int num=1;
int m=a[i].e ;
for(j=i+1;j<N;j++)
{
if(a[j].s >=m)
{
num++;
m=a[j].e ;
}
}
sum=max(sum,num);
}
cout<<sum<<endl;
return 0;
}
还有一种
#include<bits/stdc++.h>
using namespace std;
struct node{
int s,e;
}a[10010];
bool cmp(node x,node y)
{
if(x.e !=y.e )//终点若不相等,从小到大排
return x.e<y.e ;
else
return x.s <y.s; //终点相等时,起点从小到大排
}
int N,i,j;
int main()
{
cin>>N;
for(i=0;i<N;i++)
cin>>a[i].s >>a[i].e ;
sort(a,a+N,cmp);
int num=1;
int m=a[0].e ;
for(i=0;i<N;i++)
{
if(a[i].s >=m)
{
num++;
m=a[i].e ;
}
}
cout<<num<<endl;
return 0;
}