Description
在一个夜黑风高,下着暴风雨的夜晚,农民约翰的牛棚的屋顶、门被吹飞了。 好在许多牛正在度假,所以牛棚没有住满。 剩下的牛一个紧挨着另一个被排成一行来过夜。 有些牛棚里有牛,有些没有。 所有的牛棚有相同的宽度。 自门遗失以后,农民约翰必须尽快在牛棚之前竖立起新的木板。 他的新木材供应商将会供应他任何他想要的长度,但是供应商只能提供有限数目的木板。 农民约翰想将他购买的木板总长度减到最少。 给出:可能买到的木板最大的数目M(1<= M<=50);牛棚的总数S(1<= S<=200); 牛棚里牛的总数C(1 <= C <=S);和牛所在的牛棚的编号stall_number(1 <= stall_number <= S),计算拦住所有有牛的牛棚所需木板的最小总长度。 输出所需木板的最小总长度作为答案。
Input
1 行: M , S 和 C(用空格分开) 2 到 C+1行: 每行包含一个整数,表示牛所占的牛棚的编号。
Output
单独的一行包含一个整数表示所需木板的最小总长度。
Sample Input
4 50 18 3 4 6 8 14 15 16 17 21 25 26 27 30 31 40 41 42 43
Sample Output
25
题解:
最多可以买m块木板(长度不限),共有s个牛棚,这些牛棚全都没有门,其中c个牛棚里有牛,问:需要买的木板的最小的总长度。
只需要给有牛的棚子买门即可,但是,因为有木板个数的限制,所以需要给某些没有牛的棚子买,把几块不连续的木板连成一块。
把不连续编号的长度放在一个数组中,把该数组中前 m-1 个大的数舍弃,其他的全部加上,就能保证只买 m 块木板。
注意:记得要对输入的牛棚编号排序。
代码如下:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#define MAXN 0x3f3f3f3f
using namespace std;
typedef long long LL;
int cmp(int a,int b)
{
return a > b;
}
int main()
{
int a[222],b[222],c[222];
int m,s,k,o=0;
cin >> m >> s >> k;
for(int i=1; i<=k; i++)
cin >> a[i];
sort(a+1,a+k+1);
for(int i=2; i<=k; i++)
{
if(a[i]-a[i-1]!=1)
c[o++]=a[i]-a[i-1]-1; //不连续的编号的长度
}
if(o<m) //o为间隔数,则所需木板个数为o+1,o<m表示所需木板个数小于或等于m
cout << k <<endl;
else
{
sort(c,c+o,cmp);
for(int i=m-1; i<o; i++) //前m-1个舍弃
k += c[i];
cout << k <<endl;
}
return 0;
}