POJ 2376 Cleaning Shifts 贪心

来源:互联网 发布:java培训周末班 编辑:程序博客网 时间:2024/04/23 19:00
C - Cleaning Shifts
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu
Submit Status Practice POJ 2376

Description

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开始那一定不满足条件,

ac代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n,t;
struct fun  
{  
    int a;
int b;  
}s[25010]; 
int cmp(fun x,fun y)
{  if(x.a==y.a)
   return x.b<y.b;
   else 
    return x.a<y.a;
     
 } 
int main()
{    int i,j;
     int count=1; 
     int time;
     int max;
   scanf("%d %d",&n,&t);
    for(i=1;i<=n;i++)
   scanf("%d %d",&s[i].a,&s[i].b);
        sort(s+1,s+1+n,cmp);
       if(s[1].a!=1)
         { printf("-1\n");
          return 0;}
       else{
          time=s[1].b;
          i=2;
          while(s[i].a==1)
          {  time=s[i].b;
             i++;
 }
}//这里是为了找到起始开始时间中结束最晚的;
          while(time<t)
          {   if(i>n)
               break;
               j=i;
               max=s[i].b;
               i++;
               while(i<=n&&s[i].a<=time+1)//找到和前一个结束时间最接近的开始时间,并且要求结束时间也最晚的那一个;
               {  if(s[i].b>max)
                  {  j=i;
   max=s[i].b;}
   i++;

if(max<=time||s[j].a>time+1)
break;
else{
count++;
time=s[j].b;}
 }
 if(time<t)
 printf("-1\n");
 else
printf("%d\n",count);
return 0;
 } 

0 0
原创粉丝点击