Description
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
* 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
Sample Input
3 10 1 7 3 6 6 10
Sample Output
2
Hint
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
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<queue>
using namespace std;
//题意:农夫有N头牛。现在他想让一些牛去做家务。然后他把一天分成T个时间点,也就是一天的时间点是区间[1,T]。他想要任何一个时间点都有牛在做家务。现在给出每头牛的工作时间,问你能否用最少的牛满足他的要求,即用最少的时间段覆盖掉这一天([1,T])。如果不能满足则输出-1,否则输出最少的牛数量。
//分析:贪心题。题目意思很明显是求最少的区间覆盖掉大区间。先对这些时间段排好序(见代码),这个排序应该是没什么问题的。然后呢,第一头牛肯定要选,就从这头牛开始,选取下一头牛。下一头牛怎么选取呢?即在满足条件的牛里面(注意:满足条件的牛是只要开始工作时间 start>=cow[0].y+1 即可),选取右边界值最大的那个,因为这样子能够覆盖掉最多的时间段。以此类推,故贪心法求之。
struct node
{
int s,e;
};
bool cmp(node a,node b)
{
if(a.s==b.s)
return a.e>b.e;
return a.s<b.s;
}
int main()
{
int n,t,i,j,X,Y;
node a[25005];
X=Y=0;
cin>>n>>t;
for(i=1;i<=n;i++)
{
scanf("%d%d",&a[i].s,&a[i].e);
if(a[i].s==1) X=1;
if(a[i].e==t) Y=1;
}
sort(a+1,a+1+n,cmp);
if(X==0||Y==0)
cout<<-1<<endl;
else
{
int start=a[1].e;
int maxy=a[1].e;
int ans=1,sum=1;
while(1)
{
while(ans+1<=n&&a[ans+1].s<=start+1)
{
ans++;
if(a[ans].e>maxy)
maxy=a[ans].e;
}
if(maxy!=start)
{
sum++;
start=maxy;
}
else
{
//cout<<1<<endl;
// break;
if(ans==n)
{
cout<<sum<<endl;
break;
}
else
{
cout<<-1<<endl;
break;
}
}
}
}
}
解决农夫约翰的问题,通过最少数量的牛来确保每个时间段都有牛在做家务。此问题需运用贪心算法,对牛的工作时间进行排序并选择覆盖最大区间的牛。
246

被折叠的 条评论
为什么被折叠?



