算法入门课第一节–练习–Selfish Grazing 题解

算法入门课第一节–练习–Selfish Grazing 题解


来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

Each of Farmer John’s N (1 <= N <= 50,000) cows likes to graze in a certain part of the pasture, which can be thought of as a large one-dimeensional number line. Cow i’s favorite grazing range starts at location Si and ends at location Ei (1 <= Si < Ei; Si < Ei <= 100,000,000).
Most folks know the cows are quite selfish; no cow wants to share any of its grazing area with another. Thus, two cows i and j can only graze at the same time if either Si >= Ej or Ei <= Sj. FJ would like to know the maximum number of cows that can graze at the same time for a given set of cows and their preferences.

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.

输入格式:

  • Line 1: A single integer: N
  • Lines 2..N+1: Line i+1 contains the two space-separated integers: Si and Ei

输出格式:

  • Line 1: A single integer representing the maximum number of cows that can graze at once.

样例:

输入:

5 
2 4 
1 12 
4 5 
7 10 
7 8 

输出:

3

Solution

思路:

贪心算法,建立结构体进行排序,以右端点越靠前为最优贪心解。

代码:

#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
struct node{
    ll a,b;
}a[50005];

bool cmp(node tx,node ty){
    if(tx.b<ty.b) return true;
    if(tx.b>ty.b) return false;
    if(tx.a<ty.a) return true;
    return false;
}

int main(){
    ll n;
    cin>>n;
    for(int i = 0;i<n;i++){
        cin>>a[i].a>>a[i].b;
    }

    sort(a,a+n,cmp);
    ll cnt = 0,r=0;
    for(int i  = 0 ;i<n;i++){
        if(a[i].a >= r){
            cnt++;
            r = a[i].b;
        }
    }
    cout<<cnt;


    return 0;
}
算法题解 文章被收录于专栏

主要发布算法题解,题目来源牛客、codeforces、洛谷、Atcoder、leetcode

全部评论

相关推荐

zzzilik:四个月实习做了3个项目不觉得很假吗,真没必要写这么多吧我感觉挑点核心的重点写一下我感觉会好点
你的简历改到第几版了
点赞 评论 收藏
分享
11-23 15:14
中原工学院 Java
程序员花海_:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务