USACO section1.3.2 Barn Repair

1. 这道题想多了,想得很复杂,其实就是把输入的一排数按照从小到大的顺序排列,然后得到相邻两个数之间的差,按从大到小的顺序排序,用这个数组所有元素的和减去前m-1个数,然后再加上m,就得到结果

2. 以下是我的代码:

/*
ID: dollar4
PROG: barn1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstring>

using namespace std;
bool cmp1(int a, int b)
{
    return a > b;
}
bool cmp2(int a, int b)
{
    return b > a;
}
int main()
{
    ofstream fout ("barn1.out");
    ifstream fin ("barn1.in");
    int m, s, c, i, sum = 0;
    int a[201], b[201];
    memset(b, 0, sizeof(b));
    memset(a, 0, sizeof(a));
    fin >> m >> s >> c;
    for (i = 0; i < c; i++)
        fin >> a[i];
    sort(a, a + c, cmp2);
    for (i = 0; i < c - 1; i++)
    {
        b[i] = a[i+1] - a[i];
        sum += b[i];
    }
    sort(b, b + c - 1, cmp1);
    for (i = 0; i < m - 1; i++)
    {
        sum -= b[i];
    }
    if (m > c)
        fout << sum + c << endl;
    else fout << sum + m << endl;
    return 0;
}

3. 以下是官方代码:

If we can purchase M boards, then we can leave unblocked M-1 runs of stalls without cows in them, in addition to any stalls on the leftmost side that don't have cows and any stalls on the rightmost side that don't have cows.

We input the list of cows in stalls, storing into an array whether or not there is a cow in a particular stall. Then we walk the array counting sizes of runs of cowless stalls. We sort the list of sizes and pick the M-1 largest ones as the stalls that will remain uncovered.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define MAXSTALL 200
int hascow[MAXSTALL];

int
intcmp(const void *va, const void *vb)
{
	return *(int*)vb - *(int*)va;
}

void
main(void)
{
    FILE *fin, *fout;
    int n, m, nstall, ncow, i, j, c, lo, hi, nrun;
    int run[MAXSTALL];

    fin = fopen("barn1.in", "r");
    fout = fopen("barn1.out", "w");
    
    assert(fin != NULL && fout != NULL);

    fscanf(fin, "%d %d %d", &m, &nstall, &ncow);
    for(i=0; i<ncow; i++) {
	fscanf(fin, "%d", &c);
	hascow[c-1] = 1;
    }

    n = 0;	/* answer: no. of uncovered stalls */

    /* count empty stalls on left */
    for(i=0; i<nstall && !hascow[i]; i++)
	n++;
    lo = i;

    /* count empty stalls on right */
    for(i=nstall-1; i>=0 && !hascow[i]; i--)
	n++;
    hi = i+1;

    /* count runs of empty stalls */
    nrun = 0;
    i = lo;
    while(i < hi) {
	while(hascow[i] && i<hi)
	    i++;

	for(j=i; j<hi && !hascow[j]; j++)
	    ;

	run[nrun++] = j-i;
	i = j;
    }

    /* sort list of runs */
    qsort(run, nrun, sizeof(run[0]), intcmp);

    /* uncover best m-1 runs */
    for(i=0; i<nrun && i<m-1; i++)
	n += run[i];

    fprintf(fout, "%d\n", nstall-n);
    exit(0);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值