51node1091 线段的最长交集(贪心)
2016-05-02 15:24
351 查看
X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。
排序之后直接贪心就可以了。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。
排序之后直接贪心就可以了。
#include <cstdio> #include <cmath> #include <iostream> #include <algorithm> using namespace std; int const maxn = 50005 ; struct node { long long l,r; }A[maxn]; bool cmp(node a,node b) { if(a.l!=b.l)return a.l<b.l; return a.r<b.r; } int main() { int n ; while(scanf("%d",&n)!=EOF) { for(int i = 0 ; i < n ; i++) { scanf("%I64d%I64d",&A[i].l,&A[i].r); } sort(A,A+n,cmp); long long ans = 0 ; long long maxx = A[0].r ; for(int i = 1 ; i < n ; i++) { if(A[i].l<=maxx) { ans = max(ans,min(maxx,A[i].r)-A[i].l); } //cout<<ans<<endl; maxx = max(A[i].r,maxx); } printf("%I64d\n",ans); } return 0; }
相关文章推荐
- 《Nodejs开发加密货币》之六:Commander介绍
- Ubuntu 14.04 / 15.04 node.js V4.0.0
- Light oj 1094 - Farthest Nodes in a Tree【树的直径】
- 开发基于NodeJS的秘室聊天室
- leetcode-116. Populating Next Right Pointers in Each Node
- 43-Reverse Nodes in k-Group
- Light OJ 1094 - Farthest Nodes in a Tree【树的直径 两次bfs】
- leetcode:25. Reverse Nodes in k-Group
- 【LeetCode】Swap Nodes in Pairs 解题报告
- [LeetCode#2][C]Add Two Numbers
- NodeJS学习笔记
- nodejs 生产环境配置
- nodejs项目mysql使用sequelize支持存储emoji
- 深入浅出Nodejs
- leetcode——117——Populating Next Right Pointers in Each Node II
- nodejs笔记之:事件驱动,线程池,非阻塞,异常处理等
- [git]ssh: Could not resolve hostname github.com: nodename nor servname provided, or not known
- leetcode——116—— Populating Next Right Pointers in Each Node
- nodejs 核心模块crypto
- 42-Remove Nth Node From End of List