51 nod 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<iostream>
#include<algorithm>
using namespace std;
struct inp{
	int s;
	int e;
}node[50002];
bool cmp(inp a,inp b){
	if(a.s==b.s)
	  return a.e<b.e;
	else
	  return a.s<b.s;
}
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	  cin>>node[i].s>>node[i].e;
	sort(node,node+n,cmp);
	int ans=0;
	inp m=node[0];
	for(int i=1;i<n;i++)
	{
		
		if(node[i].e>=m.e)
		{
		  ans=max(ans,m.e-node[i].s);
		  	m=node[i];
	    }
	    else{
	    	ans=max(ans,node[i].e-node[i].s);
		}
	}
	cout<<ans<<endl;
	return 0;
}

 ps:我只是个拿锤子的约德尔人!

扫描二维码关注公众号,回复: 2561792 查看本文章

猜你喜欢

转载自blog.csdn.net/LOOKQAQ/article/details/81365952