POJ 2376(Cleaning Shifts)

题目链接:http://poj.org/problem?id=2376

题意:N头奶牛完成指定时间段内的任务,每头奶牛能工作的时间一定,问至少需要多少头奶牛

思路:简单的贪心区间问题。

   1.把每头奶牛起始的工作时间排序

   2.满足条件:第n头奶牛的工作开始时间点不大于第 n-1 头奶牛结束工作的时间点

           第n头奶牛的结束时间点时刻尽可能选大

ac代码:

#include <iostream>
#include <algorithm>
using namespace std;

#define MAX_N 25005

// int timi[MAX_N][2]; //一开始想用数组,但是二维数组排序不是很方便,就改用结构体
int N,T;

struct node
{
    int startt;
    int endt;
}cow_n[MAX_N];

// sort()函数自定义排序
bool Cmp(const node& a,const node& b){
    // if(a.startt!=b.startt)    return a.startt<b.startt;
    // else    return a.endt>b.endt;
    return a.startt<b.startt||(a.startt==b.startt&&a.endt>a.endt);
}

int solve(){
    int ans=0,end=0,flage=0;    //定义工作开始与结束时间    
    while(end<T){
        int begin=end+1;
        for(int i=flage;i<N;i++){
            // 首先遍历所有覆盖起点的
            if(cow_n[i].startt<=begin){
                if(cow_n[i].endt>=begin){
                    end=max(end,cow_n[i].endt);
                }
            }else{
                flage=i;
                break;
            }
        }
        if(begin>end)    
            return -1;
        else    
            ans++;
    }
    return ans;
}

int main(void){
    
    cin>>N>>T;
    for(int i=0;i<N;i++){
        cin>>cow_n[i].startt>>cow_n[i].endt;
    }
    sort(cow_n,cow_n+N,Cmp);
    cout<<solve()<<endl;

    return 0;
}
View Code
扫描二维码关注公众号,回复: 10083947 查看本文章

猜你喜欢

转载自www.cnblogs.com/jaszzz/p/12549312.html
今日推荐