USACO Barn Repair

题意:s个无门的牛屋(1~s),有c个里面有牛,每个牛屋为一格,求最少用几格木板为所有有牛的屋子装门。注意,木板最多可用m条,每条都不限长度。

思路:先给有牛的屋子序号排序,求出相邻有牛的屋子的间隔,按 从大到小排序。用第一个和最后一个有牛的屋子的总厂减去前m-1个间隔的长度,即为答案。

亦即,选出m-1个最长的间隔空出,剩余的m个区间用长木板盖门。

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #define N 205
 4 
 5 int cmp(const void * a, const void * b)
 6 {
 7     return *((int *)a) - *((int *)b);
 8 }
 9 int cmp2(const void * a, const void * b)
10 {
11     return *((int *)b) - *((int *)a);
12 }
13 
14 int main()
15 {
16     FILE *fin = fopen("barn1.in","r");
17     FILE *fout = fopen("barn1.out","w");
18 
19     int m, s, c, a[N], b[N];
20     fscanf(fin, "%d%d%d",&m, &s, &c);
21     for(int i=0; i<c; i++)
22         fscanf(fin, "%d",&a[i]);
23     qsort(a, c, sizeof(int), cmp);
24     for(int i=0; i<c-1; i++)
25         b[i] = a[i+1] - a[i] - 1;
26     qsort(b, c - 1sizeof(int), cmp2);
27     int ans = a[c-1] - a[0] + 1;
28     for(int i=0; i<m-1 && i<c-1; i++)
29     {
30         ans -= b[i];
31     }
32     fprintf(fout, "%d ",ans);
33     return 0;
34 }
View Code 
原文地址:https://www.cnblogs.com/byluoluo/p/3422919.html