不重叠的线段

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值