POJ2376 Cleaning Shifts(贪心)

来源:互联网 发布:如何做免费网络推广 编辑:程序博客网 时间:2024/05/21 09:01

题目:

Cleaning Shifts
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 22287 Accepted: 5563

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.

Source

USACO 2004 December Silver

[Submit]   [Go Back]   [Status]   [Discuss]

思路:

给了 t和n,t代表一端从1到t的区间,接下来有n段小区间,现在要从这n段小区间里面选出区间来吧从1到t这段区间覆盖掉,问最少选取几个区间,如果不能覆盖输出-1

我们的思路可以这样:

先对每个区间的起点从小到大排序,然后开始遍历这些区间。设置一个变量ed来记录当前已经确定区间的最右端,然后我们可以每次选取所有的左端点小于ed的区间,在里面找出右端点的最大值,然后更新最右端点。

代码:

#include <cstdio>#include <cstring>#include <string>#include <set>#include <iostream>#include <cmath>#include <stack>#include <queue>#include <vector>#include <algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define inf 0x3f3f3f3f#define mod 10000007#define debug() puts("what the fuck!!!")#define N (1010000)#define ll long longusing namespace std;struct node{int st,ed;} a[N];bool cmp(node a,node b){if(a.st==b.st)return a.ed<b.ed;elsereturn a.st<b.st;}int main(){int t,n;while(~scanf("%d%d",&n,&t)){int sum=0,ed=0,temp=0,flag=0;a[n+1].st=inf;for(int i=1; i<=n; i++)scanf("%d%d",&a[i].st,&a[i].ed);sort(a+1,a+n+1,cmp);for(int i=1; i<=n; i++){if(a[i].st<=ed+1){if(temp<a[i].ed){temp=a[i].ed;flag=1;}if(a[i+1].st>ed+1&&flag)//把区间向外延伸{ed=temp;sum++;//选取a[i]的区间flag=0;}}}if(ed<t)puts("-1");elseprintf("%d\n",sum);}return 0;}


原创粉丝点击