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 10
1 7
3 6
6 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.
首先是排序,如果开始区间不同,则小的在前面,如果相同,则结束端点小的在前面,这样就能保证i从1开始遍历的过程中满足条件的区间如果开始端点相同,那么后面的区间一定优于前面的区间。
fstart和fend就是标记区间最左最右是否覆盖了1到t。
再就是right和tright,在遍历的过程中,不需要记录左端点(但是需要判断左端点是否满足条件),如果左端点满足条件,那么就找到区间向右延伸的最大值。while出来后,两种情况,tright和right是否相等,不相等意味着在上一个被确定的牛管理的区间可以和下一个区间接起来,并且在这里直接判断right是否大于等于t了。也就意味着如果tright和right如果相等就是对于上一个确定的区间,没有另一个区间能够和他接起来。 PS:。
using namespace std;
typedef struct{
int start, end;
}node;
node cow[25005];
int cmp(node a, node b)
{
if (a.start!=b.start)
return a.start<b.start;
return a.end<b.end;
}
int main()
{
int n, t;
int fstart=0, fend=0;
scanf("%d%d", &n, &t);
for (int i=1; i<=n; i++){
scanf("%d%d", &cow[i].start, &cow[i].end);
if (cow[i].start==1) fstart=1;
if (cow[i].end==t) fend=1;
}
if (fstart==0||fend==0){
printf("-1");
return 0;
}
sort(cow+1, cow+n+1, cmp);
int pos=1, right=0, tright=1, ans=0;
while (true){
while (pos<=n && cow[pos].start<=right+1){//right一开始必须是0
if (cow[pos].end>tright)
tright=cow[pos].end;
pos++;
}
if (right!=tright){
right=tright;
ans++;
if (right>=t)
break;
}else{
printf("-1");
return 0;
}
}
printf("%d", ans);
return 0;
}