Cleaning Shifts 题解

来源:互联网 发布:电子画板手绘软件 编辑:程序博客网 时间:2024/06/06 01:30

关于Cleaning Shifts的一些解题思路

先贴题目
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 10
    1 7
    3 6
    6 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.
题目抽象的来说就是用贪心思想去求解用最少的线段,去覆盖整个线段长度。
回归正题
首先既然要贪心的思想,就要做排序操作。
然后我用了cnt来统计需要的数量,用sum来比较每一次末端的长度,用end来确定每一次的末端。

#include <iostream>#include<algorithm>#include <stdio.h>using namespace std;struct node{    int  a,b;};struct node a[2500005];bool cmp(node a,node b){    if(a.a==b.a) return a.b>b.b;    else return a.a<b.a;}//结构体排序的比较函数int main(){    int  t,n;    scanf("%d%d",&n,&t);    for(int i=1; i<=n; i++)    {        scanf("%d%d",&a[i].a,&a[i].b);    }//习惯从1开始写    sort(a+1,a+1+n,cmp);//排序    if(a[1].a!=1)    {        printf("-1\n");        return 0;    }//如果开头值都做不到等于1,那不管后面如何肯定覆盖不了所有区间    int end=a[1].b,sum=end,cnt=1;//因为先确定了end,所以cnt的值为1    for(int i=2; i<=n; i++)    {        if(a[i].a<=end+1)        {            sum=max(sum,a[i].b);        }//若每次比较的左断点在上一段区间的里面或等于end+1即end的旁边,就不断进行比较满足条件中最远的点,即sum最大。        else        {            end=sum;            if(a[i].a>end+1)            {                printf("-1\n");                return 0;            }            else            {                cnt++;                if(a[i].a<=end+1)                {                    sum=max(sum,a[i].b);                }            }        }    }    if(end!=sum)    {        cnt++;        end=max(sum,end);    }    if(end!=t) printf("-1\n");    else printf("%d\n",cnt);    return 0;}
原创粉丝点击