USACO 1.3 Barn Repair (Greedy), USACO Barn
This question is also greedy.
To minimize the total length of a wooden board, the maximum length of the uncovered wooden board is required.
We first use a piece of wooden board to cover the cowshed. Then, each time we select the largest gap from the covered range, divide the wooden board into two blocks Based on the gap, and repeat until it is divided into m blocks or there is no gap.
/* ID:twd30651 PROG:barn1 LANG:C++*/#include<iostream>#include<fstream>#include<stdlib.h>//#define DEBUGusing namespace std;int M;int S;int C;int origin_data[300];int process_data[300];int comp(const void*a,const void*b){ return*(int*)a-*(int*)b;}int comp2(const void*a,const void*b){ return*(int*)b-*(int*)a;}int main(int argc,char *argv[]){ freopen("barn1.in","r",stdin); freopen("barn1.out","w",stdout); scanf("%d %d %d",&M,&S,&C); int i=0; int min=300; int max=0; while(scanf("%d",&origin_data[i])==1) { if(origin_data[i]>max)max=origin_data[i]; if(origin_data[i]<min)min=origin_data[i]; i++; } qsort(origin_data,i,sizeof(int),comp);#if defined(DEBUG) for(int j=0;j<i;++j) printf("%d ",origin_data[j]); printf("\n");#endif int j; for(j=1;j<i;++j){ process_data[j-1]=origin_data[j]-origin_data[j-1]-1;#if defined(DEBUG) printf("%d ",process_data[j-1]);#endif } qsort(process_data,j-1,sizeof(int),comp2);#if defined(DEBUG) printf("max is %d min is %d\n",max,min);#endif int total=max-min+1; for(int i=0;i<M-1;++i){#if defined(DEBUG) printf("process data %d\n",process_data[i]);#endif total-=process_data[i]; } printf("%d\n",total); return 0;}
Dp can be used on the Internet.