有一排牛棚,其中某些有牛有些没有,每个棚宽度相同,要求用不超过规定的木板数覆盖最少的牛棚,前提当然是有牛的棚都要覆盖啦。很典型的贪心问题,反过来想比较容易,要覆盖最少,也就是空出最多。这样算法就很清楚了,从第一个被占据的牛棚开始数,到最后一个被占据的牛棚为止,找出所有的空牛棚,把它们排序,删掉最长的那些就ok了。
#include <iostream>
#include <fstream>
using namespace std;
int compare(const void *p, const void *q){
return *(int*)q - *(int*)p;
}
int main(){
int M, S, C, start, end;
ifstream fin("barn1.in");
fin>>M>>S>>C;
// initialization
int *barn = new int[S];
for(int i = 0; i < S; ++i) barn[i] = 0;
// start is first non-zero position
// end is last non-zero position
start = S; end = 0;
for(int i = 0; i < C; ++i){
int tmp;
fin>>tmp;
if(start > tmp) start = tmp;
if(end < tmp) end = tmp;
barn[tmp]++;
}
int p = start, blank, j = 0;
int *sn = new int[S];
while(p <= end){
blank = 0;
// step to empty barn
while(barn[p]&&p <= end) p++;
// step to next occupied barn and
// accumulate # of empty barns
while(!barn[p]&&p <= end){blank++; p++; }
// record this consecutive barns
sn[j++] = blank;
}
int stalls = end - start + 1; // final number
int s; // get actual # of boards needed
if(j > M) s = M;
else s = j;
// sort as reverse order to get first (M - 1) biggest blank barns
// NOTE: only sort when # of blank barns greater than 2
if(j > 2) qsort(sn, j - 1, sizeof(int), compare);
for(int i = 0; i < s - 1; ++i) stalls -= sn[i];
ofstream fout("barn1.out");
fout<<stalls<<endl;
delete[] sn;
delete[] barn;
}