这题贪心法,首先按照每头牛工作开始时间进行升序排序,然后在按顺序选取雇佣的牛,选择的时候要满足:
1,当前查询的牛的开始工作时间小于等于上一次选中的牛的工作结束时间;
2,当前查询的牛工作结束时间最晚。
当依次查询完毕后,就能得到答案。
#ifndef HEAD
#include <stdio.h>
#include <vector>
#include <math.h>
#include <string.h>
#include <string>
#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stack>
#include <map>
using namespace std;
#endif // !HEAD
struct TimeSeg
{
int start;
int end;
};
bool CSSortor(TimeSeg& a1, TimeSeg& a2)
{
return a1.start < a2.start;
}
int main()
{
#ifdef _DEBUG
freopen("e:\\in.txt", "r", stdin);
#endif
int n, m;
scanf("%d %d\n", &n, &m);
vector<TimeSeg> vecTS;
for (int i = 0; i < n; i++)
{
TimeSeg ts;
scanf("%d %d\n", &ts.start, &ts.end);
vecTS.push_back(ts);
}
sort(vecTS.begin(), vecTS.end(), CSSortor);
TimeSeg ts;
ts.start = m + 1;
ts.end = 0;
vecTS.push_back(ts);
int start = 0;
int maxEnd = 0;
int curCount = 0;
for (int i = 0; i < n + 1;i++)
{
if (vecTS[i].start <= start + 1 && vecTS[i].end >= maxEnd)
{
maxEnd = vecTS[i].end;
}
else if (vecTS[i].start > start + 1)
{
start = maxEnd;
curCount++;
if (vecTS[i].start <= start + 1)
{
maxEnd = max(maxEnd, vecTS[i].end);
}
else
break;
}
}
if (maxEnd >= m)
{
printf("%d\n", curCount);
}
else
printf("-1\n");
return 0;
}