您的位置:首页 > 其它

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
第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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: