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);
}


你可能感兴趣的:(USACO section1.3.2 Barn Repair)