51nod 1091 线段的重叠
来源:互联网 发布:php编写99乘法表 编辑:程序博客网 时间:2024/06/05 22:46
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示例
51 52 42 83 77 9
Output示例
4
思路:最初思路 是用dp[i]保存前i个点线段重叠的最大部分,但是如果二维循环,O(n*n)的复杂度,明显超时,但是其实只用一维就完全可以搞定了,
先按起点排序对所有点,然后找当前点前面的所有线段终点最靠后的那根,就跟当前线段有最大的重合,长度就是那个线段的终点减去当前线段的起点,但是有一种情况就是那个线段的终点超过了当前线段的终点,那么重合的长度就是当前线段的长度,那根线段覆盖当前长度。只要每次保存最大值就行,这样排序复杂度nlogn,一次遍历n,总复杂度是nlogn。
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct node{ int x,y;}p[50001];int cmp(node a,node b){ if(a.x!=b.x) return a.x<b.x; else return a.y<b.y;}int main(){ //freopen("a.txt","r",stdin); int n,i,j,maxn=0; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d%d",&p[i].x,&p[i].y); sort(p,p+n,cmp); int m=p[0].y; for(i=1;i<n;i++) { if(p[i].y>=m) { maxn=max(maxn,m-p[i].x); m=p[i].y;} else maxn=max(maxn,p[i].y-p[i].x); } printf("%d\n",maxn); return 0;}
阅读全文
0 0
- 51nod-1091 . 线段的重叠
- 51nod 1091 线段的重叠(贪心)
- 51nod 1091 线段的重叠
- 51nod 1091 线段的重叠
- 51nod 1091 线段的重叠 贪心
- 51nod 1091 线段的重叠
- 51nod 1091 线段的重叠 贪心
- 贪心-51nod 1091 线段的重叠
- 51nod-【1091 线段的重叠】
- 51nod 1091 线段的重叠
- 51nod 1091 线段的重叠
- 51nod 1091 线段的重叠
- 51 NOD 1091 线段的重叠
- 51Nod 1091 线段的重叠
- 51 nod 1091 线段的重叠
- 51Nod-1091 线段的重叠【排序】
- 51Nod 1091 线段的重叠
- 51nod 1091 线段的重叠
- Git-时光穿梭
- 去哪儿网任务系统演进
- Codeforces 842 D Vitya and Strange Lesson
- windows安装git
- 【MYSQL】查询不区分大小写
- 51nod 1091 线段的重叠
- bigDecimal作为参数传入方法中累加的坑
- ios水波纹效果
- Gti学习中“Please tell me who you are.”的解决
- UITableView什么时候使用,UITableView的使用条件使用场景,哪些情况不需要使用UITableView
- qt 通过http获取网络图片并且显示
- Android Listview加载不同布局,ViewHolder类型转换异常!!!
- 冰风1
- 流式统计的几个难点