USACO Barn Repair----贪心

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.

PROGRAM NAME: barn1

INPUT FORMAT

Line 1: M, S, and C (space separated)
Lines 2-C+1: Each line contains one integer, the number of an occupied stall.

SAMPLE INPUT (file barn1.in)

4 50 18
3
4
6
8
14
15
16
17
21
25
26
27
30
31
40
41
42
43

OUTPUT FORMAT

A single line with one integer that represents the total number of stalls blocked.

SAMPLE OUTPUT (file barn1.out)

25
[One minimum arrangement is one board covering stalls 3-8, one covering 14-21, one covering 25-31, and one covering 40-43.]

题意:简化为在一条线上有c个点,现在你可以买等于或者小于m块板子去把这c个点都覆盖了,问所买的板子的最小总长度。

一开始真不知道怎么去贪心,看了别人的思路才豁然开朗。

确实板子越多总长度才会越小。所以我们首先假设每个点都有一块板子,然后就开始拆板子,先拆距离最大的,直到拆成只剩m块板子为止。

#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<fstream>
#include<math.h>
#include<string.h>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
ifstream fin("barn1.in");
ofstream fout("barn1.out");
int m,s,c;
int a[205];
struct Node
{
    int id,d;
}node[205];
int cmp(Node x,Node y)
{
    return x.d>y.d;
}
int cmp2(Node x,Node y)
{
    return x.id<y.id;
}
int main()
{
    fin>>m>>s>>c;
    for(int i=0;i<c;i++)
    fin>>a[i];
    sort(a,a+c);
    if(m==1) {fout<<(a[c-1]-a[0]+1)<<endl;}
    else
    {
    int h=0;
    for(int i=1;i<c;i++)
    {
        node[h].d=a[i]-a[i-1];
        node[h++].id=i;
    }
    sort(node,node+c-1,cmp);
    for(int i=0;i<m-1;i++)
    node[i].d=-1;
    sort(node,node+c-1,cmp2);
    int count=0;
    int pi=0;
    int i;
    for(i=0;i<c-1;i++)
    {
        if(node[i].d==-1)
        {
            count+=a[i]-a[pi]+1;
            pi=i+1;
        }
    }
    count+=a[c-1]-a[pi]+1;
    fout<<count<<endl;
    }
    return 0;
}


 

 

你可能感兴趣的:(USACO Barn Repair----贪心)