USACO 1.3.2 Barn Repair (barn1)

1、贪心算法:先用一块木板盖住牛棚,然后,每次从盖住的范围内选一个最大的空隙,以空隙为界将木板分成两块,重复直到分成m块或没有空隙。

/* ID: gengjia1 LANG: C TASK: barn1 */ #include <stdio.h> #include <stdlib.h> #include <string.h> //#define NDEBUG #include <assert.h> #define MAX_STALL 200 int M, S, C; /* 降序 */ int intcompare (const void * a, const void * b) { return ( *(int*)b - *(int*)a ); } int main(void) { FILE *fin = fopen ("barn1.in", "r"); FILE *fout = fopen ("barn1.out", "w"); assert(fin != NULL && fout != NULL); int s[MAX_STALL+1] = {0}; int d[MAX_STALL] = {0}; int current; int last; int minlen; int count = 1; /* 木板的数目 */ int i, j; fscanf (fin, "%d", &M); assert(M >= 1); assert(M <= 50); fscanf (fin, "%d", &S); assert(S >= 1); assert(S <= MAX_STALL); fscanf (fin, "%d", &C); assert(C >= 1); assert(C <= S); for(i = 0; i < C; i++) { fscanf(fin, "%d", &current); assert(current <= S); s[i] = current; } /* 对牛棚序号降序排序(升降无所谓,下面必须用到降序,所以这里一样) */ qsort(s, C, sizeof(int), intcompare); /* 计算相邻两个有牛的牛棚的距离 */ j = 0; for(i = 0; i < C; i++) { current = s[i]; if(i == 0) { minlen = current; last = current; continue; } if(last - current - 1 > 0) { d[j++] = last - current - 1; } last = current; } minlen = minlen - current + 1; /* 一块木板盖住所有牛棚的长度 */ qsort(d, j, sizeof(int), intcompare); for(i = 0; i < j; i++) { if(count == M) { break; } minlen -= d[i]; count += 1; } fprintf(fout, "%d/n", minlen); fclose(fin); fclose(fout); exit(0); }  

你可能感兴趣的:(USACO 1.3.2 Barn Repair (barn1))