51nod-【1091 线段的重叠】

基准时间限制:1 秒 空间限制:131072 KB 分值: 5  难度:1级算法题
 收藏
 关注
X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。
Input
第1行:线段的数量N(2 <= N <= 50000)。
第2 - N + 1行:每行2个数,线段的起点和终点。(0 <= s , e <= 10^9)
Output
输出最长重复区间的长度。
Input示例
5
1 5
2 4
2 8
3 7
7 9
Output示例

4

按照起点从小到大排列,起点相同时,按照终点从小到大,自己画画就出来了 

#include<cstdio>
#include<algorithm>
using namespace std;
#define LL long long
struct node
{
	LL str;
	LL end; 
}arr[60000];
bool cmp(node a,node b)
{
	if(a.str!=b.str)
		return a.str<b.str;
	return a.end<b.end; 
} 
LL get_min(LL a,LL b)
{
	if(a>b)
		return b;
	return a; 
} 
LL get_max(LL a,LL b)
{
	if(a>b)
		return a;
	return b; 
} 
int main()
{
	LL n;
	while(scanf("%lld",&n)!=EOF)
	{
		LL i;
		for(i=0;i<n;++i)
			scanf("%lld%lld",&arr[i].str,&arr[i].end);
		sort(arr,arr+n,cmp);
		LL sum=0,max=arr[0].end,temp; 
		for(i=1;i<n;++i)
		{
			temp=get_min(max,arr[i].end)-arr[i].str;
			max=get_max(max,arr[i].end);
			if(temp>sum)
				sum=temp; 
		} 
		printf("%lld\n",sum); 
	} 
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值