[C++]Cleaning Shifts
Cleaning Shifts:
分配 N (1 <= N <= 25,000) 只中的一些奶牛在牛棚附近做些清洁。他总是要让至少一只牛做清洁。他把一天分成T段(1 <= T <= 1,000,000), 第一段是1,最后一段是T。每只奶牛只在一些时间段有空。奶牛如果选择某一段时间,则必须完成整段时间的工作。你的任务是帮助FJ安排一些奶牛,使每段时间至少有一只奶牛被安排来做这件事。并且奶牛数应尽可能小。如果不可能办到,输出-1
输入格式:
-
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.
输出格式: -
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.
输入:
3 10
1 7
3 6
6 10
输出:
2
解题思路:
需要使牛的工作时间将[1,T]铺满
将所有牛按开始时间从左到后排序
然后贪心选择能接任工作(与正在工作的牛有交叉点),且结束时间最远的牛
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
struct ST{
int s;
int e;
};
int n, t;
ST st[25001];
int cmp(ST a, ST b){
return a.s<b.s;
}
int main(){
scanf("%d%d", &n, &t);
for(int i = 0; i<n; i++){
scanf("%d%d", &st[i].s, &st[i].e);
}
sort(st, st+n, cmp);
int end = 0;
int pos = 0;
int ans = 0;
while(end < t){
int start = end + 1; //下头牛的起始时间
for(int i = pos; i<n; i++){
if(st[i].s <= start){ //如果与上头已工作的牛有交叉部分 则寻找最远结束时间
end = max(end, st[i].e);
}
else{
pos = i; // 所有能接任工作的牛都查过
break;
}
}
if(start > end) //没有找到能接任工作的牛
break;
ans++;
}
if(end < t)
cout<<-1<<endl;
else
cout<<ans<<endl;
return 0;
}