usaco BarnRepair题目解答

引用博客:http://blog.csdn.net/lisc741/article/details/8272454

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(木板数目),C(牛的数目)[题目描述中提到牛是一个挨着一个,其实就是指一个牛一个棚];需要求解的是木板的最短长度。思路是最短长度可以看做将第一个牛棚到最后一个牛棚都先连起来,然后去除最长的M-1个间隔(M块木板最多有M-1个间隔),剩下的木板长度就是最短长度。


代码:

bool cmp(int a, int b)
{
return a > b;
}

int main() {
    ofstream fout ("barn1.out");
    ifstream fin ("barn1.in");
int S = 0;
int C = 0;
int M = 0;
int ans = 0;
fin >> M >> S >> C;
int* stalls = new int[C];
int* gaps = new int[C];
for (int i = 0; i < C;i++)
{
fin >> stalls[i];
gaps[i] = 0;
}
sort(stalls, stalls + C);
for (int j = 0; j < C;j++)
{
if (j==0)
{
continue;
}
gaps[j - 1] = stalls[j] - stalls[j - 1]-1;//间隔去除首尾
}
sort(gaps, gaps + C, cmp);
ans = stalls[C-1] - stalls[0] + 1;
for (int k = 0; k <M-1;k++)
{
ans -= gaps[k];
if (gaps[k]==0)//当剩下的距离都是0的时候就说明剩下的牛棚都是连着的
{
break;
}
}
fout << ans << endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/yunzhilongteng/article/details/45176481