/*
PROG: barn1
LANG: C++11
*/
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <climits>
#include <ctype.h>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <deque>
#include <set>
#include <map>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define mst(a,b) memset(a,b,sizeof(a))
#define eps 10e-8
typedef long long ll;
const int N = 100010;
const ll MOD = 1000000007;
const int INF = 0x7fffffff;
int m ,s ,c, k, i;
bool stalls[500];
int main()
{
ifstream fin ("barn1.in");
ofstream fout ("barn1.out");
fin >> m >> s >> c;
for(i = 0; i < c; i++){
fin >> k;
stalls[k] = 1;
}
// get rid of both end
i = 1;
while(i <= s && !stalls[i] ){
i++;
}
vector<int> vacancy;
int empty = 0;// only when empty slots is between occupied stalls
int board = 0;
while(1){
empty = 0;
while(i <= s && !stalls[i]){
i++;
empty++;
}
if( i <= s){
board++;
if(empty)
vacancy.push_back(empty);
}
else {
break;
}
while( i <= s && stalls[i]){
i++;
}
if(i == s+1){
break;
}
}
sort(vacancy.begin(), vacancy.end());
for(int i = 0; i < board -m; i++){
c += vacancy[i];
}
fout << c << endl;
fin.close();
fout.close();
return 0;
}
贪心: 首先计算没有木板限制时为达到总length最短所需要的木板。 用合并的方式来达到减少木板的目的。每一次合并浪费掉的木板最短,结果就是最优解。
具体的一次扫描,计算初始木板个数的同时统计连续无奶牛的stall的长度,最后排序,从短的开始合并就可以了。