USACO Barn Repair 【贪心算法】

这到题目的题意不太好理解= = 

看来还是英语太弱了

实际上题目给了你M, S, C

分别代表最多不超过M 块木板, S代表牛棚总数,C代表接下来有C个牛所在牛棚的标号

然后求的是如何安排方案,可以使得总木板长度最小。

是一道【贪心】的题目。

首先得判断,如果M >= C,就直接输出C,表示最小长度为C

然后,对输入的牛进行排序

求出ans数组,表示相邻牛的牛棚间隔

再对ans数组排序

求出cnt,cnt为最后一只牛棚的牛和第一只牛棚牛的间隔

从大到小,用cnt减去ans[i],减M- 1次,表示用M块木板档牛棚

这里得注意的是,易得,用更多的木板,可以使得木板总长度最小。

Source code:

 1 /*
 2 ID: wushuai2
 3 PROG: barn1
 4 LANG: C++
 5 */
 6 //#pragma comment(linker, "/STACK:16777216") //for c++ Compiler
 7 #include <stdio.h>
 8 #include <iostream>
 9 #include <fstream>
10 #include <cstring>
11 #include <cmath>
12 #include <stack>
13 #include <string>
14 #include <map>
15 #include <set>
16 #include <list>
17 #include <queue>
18 #include <vector>
19 #include <algorithm>
20 #define Max(a,b) (((a) > (b)) ? (a) : (b))
21 #define Min(a,b) (((a) < (b)) ? (a) : (b))
22 #define Abs(x) (((x) > 0) ? (x) : (-(x)))
23 #define MOD 1000000007
24 #define pi acos(-1.0)
25 
26 using namespace std;
27 
28 typedef long long           ll      ;
29 typedef unsigned long long  ull     ;
30 typedef unsigned int        uint    ;
31 typedef unsigned char       uchar   ;
32 
33 template<class T> inline void checkmin(T &a,T b){if(a>b) a=b;}
34 template<class T> inline void checkmax(T &a,T b){if(a<b) a=b;}
35 
36 const double eps = 1e-7      ;
37 const int N = 1              ;
38 const int M = 200000         ;
39 const ll P = 10000000097ll   ;
40 const int INF = 0x3f3f3f3f   ;
41 
42 int a[222], ans[222];
43 
44 bool cmp(int a, int b){
45     return a > b;
46 }
47 
48 int main() {
49     ofstream fout ("barn1.out");
50     ifstream fin ("barn1.in");
51     int i, j, k, t, n, m, s, c;
52     memset(ans, 0, sizeof(ans));
53     fin >> m >> s >> n;
54     for(i = 0; i < n; ++i){
55         fin >> a[i];
56     }
57     if(m >= n){
58         fout << n << endl;
59         return 0;
60     }
61     sort(a, a + n);
62     for(i = 0; i < n - 1; ++i){
63         ans[i] = a[i + 1] - a[i] - 1;
64     }
65     sort(ans, ans + n - 1, cmp);
66     int cnt = a[n - 1] - a[0] + 1;
67     for(i = 0; i < m - 1; ++i){//Delete m - 1 piece
68         cnt -= ans[i];
69     }
70     fout << cnt << endl;
71     return 0;
72 }
原文地址:https://www.cnblogs.com/wushuaiyi/p/4249136.html