---
title: "Barn Repair"
author: "格桑花"
date: "2011-06-17T19:32:35Z"
tags: []
categories: ["编程语言"]
slug: "barn-repair"
draft: false
lastmod: "2011-06-17T19:32:35Z"
id: 1097112
url: "https://allcrazy.iteye.com/blog/1097112"
---

Barn Repair

题目大意：有S个牛栏，其中有C头牛在里面，一些牛栏有牛，一些没有，最大有M块的板子，每块板子的长度可以任意长，用这些板子去拦住所有的牛，使它们都被围住。求最小会有多少牛栏会被围住。

算法分析：isin~~：表示第i个牛栏里是否有牛。
          v：表示连续的没有牛的牛栏数。
         设一共有top块连续的牛栏里有牛。则可以知道：如果top<=M，则结果就是所有住有牛的牛栏数；否则的话，就需要通过中间没有牛的牛栏连接两块有牛的区域连起来，我们知道，每次这样做都会使所需用的木板数减少，但同时会增加牛栏数。此时，我们很容易想到我们只需每次选择最少数量的没有牛的牛栏块，即只需对数组v进行排序,所求的结果为所有住有牛的牛栏数+v+v+……+v。


```c++

/*
ID: xxfz014
PROG: barn1
LANG: C++
*/
#include <cstdio>
#include <algorithm>
#include <memory.h>
using namespace std;
const int maxn = 210;
int m,s,c;
bool isin[maxn];
int main()
{
    freopen("barn1.in","r",stdin);
    freopen("barn1.out","w",stdout);
    scanf("%d%d%d",&m,&s,&c);
    int a;
    memset(isin,0,sizeof(isin));
    for(int i=0;i<c;i++)
    {
        scanf("%d",&a);
        isin[a]=1;
    }
    int v[maxn],top=0;
    int sum=0,c=0;
    for(int i=1;i<=s;i++)
    {
        if(isin[i])
        {
            sum++;
            v[top++]=c;
            c=0;
        }
        else    c++;
    }
    sort(v+1,v+top);
    if(m>=top)  {printf("%d\n",sum);return 0;}
    for(int i=1;i<=top-m;i++)
    {
        sum+=v[i];
    }
    printf("%d\n",sum);
    return 0;
}


```