“21天好习惯”第一期-1

每头农场主约翰的N(1<=N<=50,000)牛喜欢在牧场的某一部分放牧,这可以被认为是一条大的一维数列。牛I最喜欢的放牧范围从Si位置开始,结束在EI位置(1<=Si<EI;Si<Ei<=100,000,000)。
大多数人都知道母牛是很自私的,没有一头牛愿意和另一只母牛分享它的牧场。因此,当Si>=EJ或EI<=Sj时,母牛I和j只能同时放牧。FJ想知道某一组牛可以同时放牧的奶牛的最大数量以及它们的偏好。
Consider a set of 5 cows with ranges shown below:
… 1 2 3 4 5 6 7 8 9 10 11 12 13 …
… |----|----|----|----|----|----|----|----|----|----|----|----|----
Cow 1: <=:=> : : :
Cow 2: <:::=>:
Cow 3: : <
> : : :
Cow 4: : : <====:=> :
Cow 5: : : <
> : :

These ranges represent (2, 4), (1, 12), (4, 5), (7, 10), and (7, 8), respectively.
For a solution, the first, third, and fourth (or fifth) cows can all graze at the same time. If the second cow grazed, no other cows could graze. Also, the fourth and fifth cows cannot graze together, so it is impossible for four or more cows to graze.

这是一种(简单)贪心算法,按end(E)排序从小到大(关键点),在比较S与前一个的E比较,如果小于E,则这俩个没有交集,故可以sum++;否则就不算;

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

#define N 50005
struct node1{
   int S;
    int E;
};
typedef struct node1 node;
 node a[N];
bool cmp(node a,node b)
{
   return a.E < b.E;
}

int main()
{
   int n,i;
    scanf("%d",&n);
   for(i=0;i<n;i++)
   {
       scanf("%d%d",&a[i].S,&a[i].E);

   }
    sort(a,a+n,cmp);
    int x = -1,sum =0;
    for(i=0;i<n;i++)
    {
        if(a[i].S>=x){
          sum++;x = a[i].E;
        } 

    }
    printf("%d",sum);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值