uva10020
2015-12-26 19:55
519 查看
题目大意:
数轴上有n个闭区间,选择尽量少的区间覆盖【0,M】
思路:
小白 154页 区间覆盖问题 贪心
首先,在区间外的区间需要去掉,只保存有包含在所求区间的区间。
然后将保存下来的区间从小到大排序,如果第一个区间的x大于0的话,就表示无解。否则,找到比0小的x,尽量找最长的(贪心思想,这样就可以找到最短的了),找到满足的最长的之后,新的起点设置为它的y坐标,并且忽略所有区间在y之间的部分。
代码:
数轴上有n个闭区间,选择尽量少的区间覆盖【0,M】
思路:
小白 154页 区间覆盖问题 贪心
首先,在区间外的区间需要去掉,只保存有包含在所求区间的区间。
然后将保存下来的区间从小到大排序,如果第一个区间的x大于0的话,就表示无解。否则,找到比0小的x,尽量找最长的(贪心思想,这样就可以找到最短的了),找到满足的最长的之后,新的起点设置为它的y坐标,并且忽略所有区间在y之间的部分。
代码:
#include <iostream> using namespace std; #include <cstring> #include <string> #include <stdio.h> #include <algorithm> struct node { int x,y; }n[100100],an[100100]; int cmp(node a,node b) { return a.x < b.x; } int main() { int cases,M,a,b,ans; scanf("%d",&cases); while(cases--) { ans = 0; scanf("%d",&M); while(1) { scanf("%d%d",&a,&b); if(a == 0 && b == 0) break; if(a > M || b < 0) //在此区间外的都要去掉 continue; n[ans].x = a; n[ans].y = b; ans++; } if(ans == 0) printf("%d\n",0); else { int min = 0,max = 0; int step = 0,pos; int f = 0; sort(n,n+ans,cmp); while(1) { if(min >= M) break; max = 0; f= 0; for(int i = 0; i < ans; i++) { //选择最长的 贪心 if(min >= n[i].x && max < n[i].y) { // 这一步纠结了好久max到底有什么用,才发现外面有一层循环 这主要是为了找到满足条件的最长的线段 // 我们找的x肯定要比它的起点还要小才可以覆盖到 y要找到最大的 才是最长的 pos = i; f = 1; max = n[i].y; } } if(f) { an[step++] = n[pos]; min = n[pos].y; // 设置新的起点 } else break; } if(f) { printf("%d\n",step); for(int i = 0 ; i < step; i++) printf("%d %d\n",an[i].x,an[i].y); } else printf("0\n"); } if(cases) printf("\n"); } return 0; }
相关文章推荐
- POJ3624 Charm Bracelet(01背包)
- centreon installing
- Win7下用Eclipse远程连接Hadoop进行开发
- linux下mysql定时备份数据库
- 记录自己的开发历程
- leetcode:219 Contains Duplicate II-每日编程第三十五题
- 好的代码行
- DS-SDOJ-数据结构实验之排序三:bucket sort
- 算法设计题2.24-线性表-第2章-《数据结构习题集》-严蔚敏吴伟民版
- 程序猿如何提高自己的搜索技能
- android中使用Application传递数据
- 【原】SDWebImage源码阅读(三)
- NGUI制作字体
- python pip源
- 墙上时钟时间 ,用户cpu时间 ,系统cpu时间
- UVA10391 Compound Words
- 测试数据的生成
- 我是好人2
- 使用Tomcat发布网站
- XenDesktop5.6连接外部SQL Server数据库步骤