51 nod 1091 贪心

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1091

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

按照左端点升序(相同时右端点升序)排列之后,对于每条线段,显然应当与之前出现过的最大的右端点比较是最优的。
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define LL  long long
 4 struct node
 5 {
 6     int s,e;
 7 }P[50005];
 8 bool cmp(node A,node B)
 9 {
10     if(A.s!=B.s) return A.s<B.s;
11     else return A.e<B.e;
12 }
13 int main()
14 {
15     int maxr,N,i,j,ans=0;
16     cin>>N;
17     for(i=1;i<=N;++i) scanf("%d%d",&P[i].s,&P[i].e);
18     sort(P+1,P+1+N,cmp);
19     maxr=P[1].e;
20     for(i=2;i<=N;++i)
21     {
22         if(maxr<P[i].s){}
23         else if(maxr>P[i].e) ans=max(ans,P[i].e-P[i].s);
24         else ans=max(ans,maxr-P[i].s);
25         maxr=max(maxr,P[i].e);
26     }
27     cout<<ans<<endl;
28     return 0;
29 }

 

posted @ 2017-08-31 11:47  *zzq  阅读(117)  评论(0编辑  收藏  举报