51nod 1133 不重叠的线段 贪心
2016-06-07 19:14
204 查看
题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1133
题目:
X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。
例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重叠。
Input
Output
对终点升序排序,然后贪心。
#include <iostream>
#include<bits/stdc++.h>
#define N 11000
using namespace std;
struct node
{
int x,y;
}a
;
bool cmp(node a,node b)
{
return a.y<b.y;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a,a+n,cmp);
int ans=1;
int ed=a[0].y;
for(int i=0;i<n;i++)
{
if(a[i].x>=ed)
{
ans++;
ed=a[i].y;
}
}
cout<<ans<<endl;
}
题目:
X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。
例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重叠。
Input
第1行:1个数N,线段的数量(2 <= N <= 10000) 第2 - N + 1行:每行2个数,线段的起点和终点(-10^9 <= S,E <= 10^9)
Output
输出最多可以选择的线段数量。
对终点升序排序,然后贪心。
#include <iostream>
#include<bits/stdc++.h>
#define N 11000
using namespace std;
struct node
{
int x,y;
}a
;
bool cmp(node a,node b)
{
return a.y<b.y;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a,a+n,cmp);
int ans=1;
int ed=a[0].y;
for(int i=0;i<n;i++)
{
if(a[i].x>=ed)
{
ans++;
ed=a[i].y;
}
}
cout<<ans<<endl;
}
相关文章推荐
- 解决android使用gson解析json字符串,并使用混淆编译方式打包apk遇到的问题
- POJ-3984-迷宫问题(BFS)
- 内部类使用方法
- STL容器的使用
- [译]好程序员的五声“呐喊”
- 安卓滑动冲突的理解和一些解决思路
- listview中EditText,焦点问题
- 第15周阅读程序(2)
- ipairs和pairs区别
- 数据库简介
- jquery 变量和原生js变量的关系
- LLVM 和Clang源代码编译
- 飛飛(五十八)虚析构函数
- Android Studio导入Vitamio多媒体开发框架 1
- Light OJ - 1008 - Fibsieve`s Fantabulous Birthday
- 权限的设计
- 第15周阅读程序(1)
- 实习面试小记-腾讯、阿里、大摩、网易
- C++符号的还原(demangling)
- 如何禁止listview的item项获得焦点,而让子控件获得焦点