原题链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1091

思路分析:通过读题不难发现这是一道涉及贪心算法的题,刚开始上手做也是摸不着头脑。首先把所有的线段按起点由小到大进行排序,比如(1,5),(2,4),(2,8),(3,7),(7,9), 然后进行比较,每次比较保留最大的末尾数字,最终结果就是 max(min(最大末尾数字,本次末尾数字)- 本次起始数字,上次的比较结果);

举个栗子:

/*
1 5
2 4
2 8
3 7
7 9
*/ // 第一次
Max = 5, ans = 0; // 第二次
Max = 5, ans = 4 - 2 = 2
// ans = max(min(5, 4) - 2, 0) = 4 // 第三次
Max = 8, ans = 5 - 2 = 3
// Max = max(5, 8) = 8, ans = max(min(5, 8) - 2, 2) = 3 // 第四次
Max = 8, ans = 7 - 3 = 4
// ans = max(min(8, 7) - 3, 3) = 4 // 第五次
Max = 8, ans = 4

代码如下:

#include <iostream>
#include <algorithm>
using namespace std; typedef pair<int, int> P;
const int MAX = 50000;
P a[MAX];
int n; int main() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i].first >> a[i].second; sort(a, a+n); int Max = a[0].second, ans = 0;
for (int i = 1; i < n; i++) {
ans = max(min(Max, a[i].second) - a[i].first, ans);
Max = max(Max, a[i].second);
}
cout << ans << endl;
return 0;
}

最新文章

  1. 常用的HTTP状态代码
  2. JavaScript-分支语句练习
  3. JAVA下的Thread.sleep方法一定要try
  4. TextView属性大全
  5. bzoj 3143 [Hnoi2013]游走(贪心,高斯消元,期望方程)
  6. SQL语句执行时所发生的步骤
  7. HDOJ/HDU 1251 统计难题(字典树啥的~Map水过)
  8. cocos2dx 各种环境的搭建
  9. 【课程分享】深入浅出嵌入式linux系统移植开发 (环境搭建、uboot的移植、嵌入式内核的配置与编译)
  10. CAN信号值解析
  11. Java中实现多线程关键词整理
  12. [国嵌攻略][173][BOA嵌入式服务器移植]
  13. 使用按钮触发element 时间事件 --时间戳
  14. 吴裕雄 python神经网络 花朵图片识别(10)
  15. Ajax(6) Ajax向servlet请求数据库操作 并显示到当前页面 这个未经测试
  16. noip第4课资料
  17. sql server2014 企业版 百度云下载
  18. layui-open-上传文件
  19. 【刷题】BZOJ 2555 SubString
  20. NOIP模拟

热门文章

  1. [BUUCTF]PWN3——warmup_csaw_2016
  2. CPU中断数查看与网卡中断绑核
  3. Python软件目录结构
  4. JS自动播放音频 无效chrome设置 (Uncaught (in promise) DOMException: play() failed because the user didn&#39;t interact)
  5. 如何获取网管MTU
  6. float浮动的详细总结
  7. VMware 打开虚拟机出现另一个程序已锁定文件的一部分,进程无法访问
  8. mybatis注解版in查询、字符串判空模糊匹配 、批量插入、插入返回主键
  9. 【LeetCode】869. Reordered Power of 2 解题报告(Python & C++)
  10. [LeetCode]621. Task Scheduler 任务安排 题解