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.
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.
中等难度的贪心,区间覆盖的类型,对于现阶段的我来说难度还是挺大的。题目的亮点是这个贪心加了一个特殊情况,就是在完成一个时间段的扫描之后,如果下一个时间段紧接着它,也是对的,如时间段[1,5]后接时间段[6,7]。这种问题,如果是用自己想的模拟算法的话,很容易出现,所以需要借鉴别人的更好的算法,完全避免了这一情况。
展示我的代码,好不容易才完成了,可惜POJ不能用#include <bits/stdc++.h>。
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
struct Node{
int s, e;
};
int N, T;
Node a[25005];
int CMP(Node x, Node y)
{
if(x.s == y.s)
return x.e <= y.e;
return x.s < y.s;
}
int main()
{
scanf("%d%d", &N, &T);
for(int i = 0; i < N; i++) {
a[i].s = a[i].e = INT_MAX;
}
for(int i = 0; i < N; i++)
scanf("%d%d", &a[i].s, &a[i].e);
sort(a, a+N, CMP);
if(a[0].s > 1) {
printf("-1");
return 0;
}
int ans = 1, id = 0;
for(int i = 0; i < N;)
{
int cnt = 0;
for(int j = i+1; j < N; j++) {
if(a[j].s > a[id].e + 1) break;
if(a[j].s >= a[id].s && a[j].e >= a[id].e + 1)
if(a[j].e > a[cnt].e) cnt = j;
}
if(cnt == 0) i++;
else {
id = cnt;
ans++;
i = id;
}
}
if(a[id].e == T) printf("%d", ans);
else printf("-1");
return 0;
}