Segment

Description

They are N segments in x-axis, each segment has a start point X, a end point Y, so it can express as [X, Y].


Now you should select two segments, they have the longest overlap length.


Segment [3, 10] and segment [7, 12] overlap in [7, 10], so the length is 3.


Input Description
The first line is case number T( T <= 10 ).
For each case, the first line is the segment number N( 1 <= N <= 100,000 ), then follow N line, each line contian Xi and Yi.( 0 <= Xi < Yi < 100,000 )
Output Description
The longest overlap length of any two segments.
Sample Input
1
5
1 5
2 4
2 8
3 7
7 9
Sample Output
4
哎。如此水的一道题。我当时既然做不出来。。。。先按边起点从小到大排序,终点也从小到大排序。注意每条边都要喝前面的终点最右的边进行比较。
 
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
inline int max(int a,int b)
{
	return a>b?a:b;
}
struct Edge
{
	int from,to;
}edge[100008];
bool cmp(Edge a,Edge b)
{
	if(a.from<b.from)return 1;
	if(a.from>b.from)return 0;
	if(a.from==b.from) 
	{
		if(a.to>b.to)return 0;
		else return 1;
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d",&edge[i].from,&edge[i].to);
		}
		sort(edge+1,edge+n+1,cmp);
		int s=edge[1].from,t=edge[1].to;
		int maxlen=0;
		for(int i=2;i<=n;i++)
		{
			if(edge[i].from<t)
			{
				if(edge[i].to<=t)
				{
					maxlen=max(maxlen,edge[i].to-edge[i].from);
				}
				else 
				{
					maxlen=max(maxlen,t-edge[i].from);
					s=edge[i].from;
					t=edge[i].to;
				}
			}
			else continue;
		}
		printf("%d\n",maxlen);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值