Poj 2376 Cleaning Shifts【贪心】

来源:互联网 发布:淘宝法院拍卖车能买吗 编辑:程序博客网 时间:2024/04/27 05:05

Cleaning Shifts
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 15656 Accepted: 3993

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.

题意:

某个人有n 头奶牛,他把一天的时间分成T段,给出每头奶牛的工作的时间段(注意是时间段!!!),问最少使用多少只奶牛才能使得一天中的所有的时刻都有至少一只奶牛在工作


题解:

贪心的区间选举问题,最小代价实现指定区间的全覆盖,贪心选举如下:

1,首先需要对每个区间的工作时间进行排序:一级排序按开始时间从小到大,二级排序按结束时间从大到小

2,,初试时间设置为0,每次选举都枚举所有的开始时间小于当前时间的区间,选取其中的结束时间最晚的作为下一次选取的区间

3,如果某个环节无法选择就跳出循环,判断是否实现了目标,否则循环到满足条件时跳出


特别注意是时间段,个人因此wa了一次...


#include<stdio.h>#include<algorithm>#include<queue>using namespace std;int n,t;struct cow{int bg,ed;}x[250005];bool cmp(cow a,cow b){if(a.bg==b.bg){return a.ed>b.ed; //结束晚的在前}return a.bg<b.bg;//开始造的在前}int slove(){sort(x,x+n,cmp); int ans=0,last=0,i=0;//从头遍历while(i<n&&last<t)//不满足条件就全部遍历 {if(x[i].bg<=last+1)//可以开始!{last=x[i].ed;++ans; //现在的时间推到奶牛工作结束时刻位置 }int tp=i+1;//尝试下一个 if(tp>=n||x[tp].bg>last+1||last==t)//越界或者接不上了 {break;}for(i=tp+1;i<n&&x[i].bg<=last+1;++i)//找能覆盖新起点,而且延伸最长的元素编号 {if(x[i].ed>x[tp].ed){tp=i;}}i=tp;//这是当前最优的选取 }return last==t?ans:-1;//判断是否完全覆盖}int main(){//freopen("shuju.txt","r",stdin);while(~scanf("%d%d",&n,&t)){for(int i=0;i<n;++i){scanf("%d%d",&x[i].bg,&x[i].ed);}printf("%d\n",slove());}return 0;} 


0 0