USCAO-Section 1.3 Barn Repair

原题:
It was a dark and stormy night that ripped the roof and gates off the stalls that hold Farmer John’s cows. Happily, many of the cows were on vacation, so the barn was not completely full.

The cows spend the night in stalls that are arranged adjacent to each other in a long line. Some stalls have cows in them; some do not. All stalls are the same width.

Farmer John must quickly erect new boards in front of the stalls, since the doors were lost. His new lumber supplier will supply him boards of any length he wishes, but the supplier can only deliver a small number of total boards. Farmer John wishes to minimize the total length of the boards he must purchase.

Given M (1 <= M <= 50), the maximum number of boards that can be purchased; S (1 <= S <= 200), the total number of stalls; C (1 <= C <= S) the number of cows in the stalls, and the C occupied stall numbers (1 <= stall_number <= S), calculate the minimum number of stalls that must be blocked in order to block all the stalls that have cows in them.

Print your answer as the total number of stalls blocked.

题意:
有一排牛圈,在其中部分牛圈中有牛,现在给你一定数量的木板(长度任意),用木板挡住所有有牛的牛圈,求怎样才能使这些木板的长度和最短,输出这个最短长度。

题解:
输入:
M 限定木板数
S 牛圈数
C 牛的数量
下面C行输入每个牛的牛圈号。

输出最短的木板长度和

因为牛圈不是每个都有牛,所以存在可以不用封堵的牛圈,使用的木板越多,长度越短(多少牛圈有牛用多少木板是最短的),所有给定的木板全部使用,在这M个木板间存在M-1个空隙,这些空隙是没有牛的牛圈连起来的,所以我们得出解法:所有牛圈的长度 - 第一个牛圈到第一个有牛牛圈的长度 - 最大的(M-1)个连着的没牛的牛圈的长度 - 最后一个有牛牛圈到最后的长度。

代码:

/*
ID:newyear111
PROG: barn1
LANG: C++
*/

#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>
using namespace std;
const int N=201;

int b[N];//记录相邻的有牛的牛圈的间隔长度 
int a[N];//记录牛所在的牛圈 
int main()
{
    ifstream fin("barn1.in");
    ofstream fout("barn1.out");

    int M,S,C;
    fin>>M>>S>>C;
    for(int i=0;i<C;i++)
        fin>>a[i];
    sort(a,a+C);//从小到大排序 
    for(int i=0;i<C-1;i++){
        b[i]=a[i+1]-a[i]-1; 
    }
    sort(b,b+C-1);//从小到大排序 
    int ans=0;
    for(int i=0;i<M-1;i++)
        ans+=b[C-i-2];
    fout<<S-ans-(a[0]-1)-(S-a[C-1])<<endl;
    fin.close();
    fout.close();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值