Cleaning Shifts(贪心算法)

来源:互联网 发布:js 强制转换字符串 编辑:程序博客网 时间:2024/06/10 04:25

Farmer John is assigning some of his N (1 <= N <= 25,000) cows to do some cleaning chores around the barn. He always wants to have one cow working on cleaning things up and has divided the day into T shifts (1 <= T <= 1,000,000), the first being shift 1 and the last being shift T. 

Each cow is only available at some interval of times during the day for work on cleaning. Any cow that is selected for cleaning duty will work for the entirety of her interval. 

Your job is to help Farmer John assign some cows to shifts so that (i) every shift has at least one cow assigned to it, and (ii) as few cows as possible are involved in cleaning. If it is not possible to assign a cow to each shift, print -1.
Input
* Line 1: Two space-separated integers: N and T 

* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.
Output
* Line 1: The minimum number of cows Farmer John needs to hire or -1 if it is not possible to assign a cow to each shift.
Sample Input
3 101 73 66 10
Sample Output
2
Hint
This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed. 

INPUT DETAILS: 

There are 3 cows and 10 shifts. Cow #1 can work shifts 1..7, cow #2 can work shifts 3..6, and cow #3 can work shifts 6..10. 

OUTPUT DETAILS: 

By selecting cows #1 and #3, all shifts are covered. There is no way to cover all the shifts using fewer than 2 cows.

题意:从1到T区间内,必须保证每个点都有牛在工作,给出每头牛的工作的起始时间和结束时间,求需用到的最小的牛的数量。

思路:

典型的贪心算法,先将每头牛的开始时间由小到大进行排序,然后贪心找到开始时间在当前牛的时间内并且结束时间在当前牛结束时间外面去贪心尽可能大的那一个。

代码:

#include <iostream>#include <cstring>#include <stdio.h>#include <algorithm>using namespace std;int n,t;struct node{int s;int e;}cow[25100];bool cmp(node a,node b)  //对开始的时间由小到大进行排序。{    if(a.s!=b.s)return a.s<b.s;    return a.e>b.e;}int ed;int main(){    int i;    while(cin>>n>>t)    {        for(i=0;i<n;i++)        cin>>cow[i].s>>cow[i].e;        sort(cow,cow+n,cmp);        if(cow[0].s>1){   //当开始时间大于1时直接输出-1            cout<<"-1"<<endl;            continue;        }        ed=cow[0].e;//先以第一个的终点作为临时终点,然后陆续更新。        int sum=1;        for(i=1;i<n;i++)        {            if(cow[i].s<=ed+1&&cow[i].e>ed)   //当一个牛开始的时间在ed+1范围内,注意时ed+1而不是ed,因为相邻的时候也可以。            {                int mark=i;                while(cow[i].s<=ed+1&&i<n)                {                    if(cow[i].e>cow[mark].e)mark=i;  //记录符合条件的位置                    i++;                }                ed=cow[mark].e;                sum++;//数量加1                i=mark;                if(ed>=t)break;  //此处>=即可不需要只等于            }        }        if(ed>=t)cout<<sum<<endl;        else            cout<<"-1"<<endl;    }    return 0;}