题意:有n头牛,他们有空的时间段是固定的。有T天,需要打扫T天的谷仓。
问:最少需要多少头牛。若不能满足,输出-1
明显贪心。需要注意的地方是,第一头牛,打扫了第一天,和第二天,下一头牛应该从第三天开始打扫。
以开始时间排序,那么我们只需要一个一个往下找最优解,边找边跟新,当不能满足开始的时间<= 少一头牛的结束时间 + 1时判断是否有有解。
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 25000 + 5;
pair<int, int> p[maxn];
bool cmp(pair<int ,int> a, pair<int, int> b)
{
if(a.first != b.first) return a.first < b.first;
else
{
return a.second < b.second;
}
}
int main()
{
int n, t;
while(scanf("%d%d", &n, &t) == 2)
{
for(int i = 0; i < n; i++)
{
int t1, t2;
scanf("%d%d", &t1, &t2);
p[i] = make_pair(t1, t2);
}
sort(p, p + n, cmp);
int pos = 0, s, e;
bool flag = true;
s = 0; e = 0;//因为从第一天开始打扫,需要使得s为零,才能满足本程序
int cnt = 0;
while(pos < n)
{
while(p[pos].first <= s + 1 && pos < n)
{
//printf("%d %d\n", p[pos].first, p[pos].second);
e = max(e, p[pos].second);
pos++;
}
if(e > s) {cnt++; s=e;}
else if(e == t) break;
else flag = false;//判断是否有解,即e是否更新
if(flag == false) break;
}
if(e < t) flag = false;
printf("%d\n", flag == false ? -1: cnt);
}
return 0;
}