USACO 1.3.2 Barn Repair

贪心算法。先用vis数组标记此栏里是否有牛(vis[i]==1表示第i栏有牛),然后用数组gap记录从此栏开始的最大空缺(比如X表示有牛,O表示没牛:XXOOOOXOX,编号从1开始。那么在这种情况下gap[2]==4,gap[7]==1,其他位置gap值均为0)。

贪心策略:统计牛一共被分成了连续的几段(设有K个位置gap不为0,则牛被分成了连续的K+1段)。然后比较能提供的最大木板数m与K+1的大小:如果m>=K+1,则说明不用覆盖空缺位置就可以完全覆盖牛,此时长度也最短(没有浪费),长度就是牛的个数。如果m<K+1,那么木板不足以把牛每段都独立覆盖,只能把几段合而为一来覆盖,此时就要注意,只需要在覆盖牛的同时覆盖前K+1-m段最短的空缺,就可以满足浪费最少,并且牛被完全覆盖。used数组表示已经被覆盖的空缺段,索引定义与gap相同,为1表示已经覆盖。

代码如下:


/*
ID: michael139
LANG: C
PROG: barn1
*/
#include<stdio.h>
#include<string.h>
int vis[205],gap[205],used[205];
int main () {
    FILE *fin  = fopen("barn1.in", "r");
    FILE *fout = fopen("barn1.out", "w");
    int m,s,c,i,j,flag,temp,left,gap_num,diff,ans,min,x;
    while (fscanf(fin,"%d%d%d",&m,&s,&c) != EOF) {
        memset(vis,0,sizeof(vis));
        memset(gap,0,sizeof(gap));
        memset(used,0,sizeof(used));
        ans = gap_num = 0;
        for (i=1;i<=c;i++) {
            fscanf(fin,"%d",&temp);
            vis[temp] = 1;
        }
        flag = vis[1];
        left = 1;
        for (i=1;i<=s;i++) {
            if (flag && !vis[i]) {
                flag = 0;
                left = i;
            } else if (!flag && vis[i]) {
                gap[left-1] = i-left;
                flag = 1;
            }
        }
        for (i=1;i<=s;i++) {
            if (gap[i]) {
                gap_num++;
            }
        }
        diff = gap_num+1-m;
        if (diff<=0) {//We can get enough boards without cover any empty stalls.
            for (i=1;i<=s;i++) {
                if (vis[i]) ans++;
            }
            fprintf(fout,"%d\n",ans);
        } else {//We must choose diff shortest gaps to be covered.
            while (diff>0) {
                min = 1000000;
                for (i=1;i<=s;i++) {
                    if (gap[i] && !used[i] && gap[i]<min) {
                        min = gap[i];
                        x = i;
                    }
                }
                used[x] = 1;
                for (i=x+1;i<=x+gap[x];i++) vis[i] = 1;
                diff--;
            }
            for (i=1;i<=s;i++) {
                if (vis[i]) ans++;
            }
            fprintf(fout,"%d\n",ans);
        }
    }
    return 0;
}


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