UVALive

题目链接:https://vjudge.net/contest/241341#problem/A

题目大意,给你n个数字,让你分成m组,每组的花费为每组的最大值-最小值,总的花费就是各组花费相加,要求总花费最小,并输出。

 

 比如这8个数字:5, 2, 3, 10, 7, 2, 6 , 8.

对于Figure 1:总花费为= (5 - 2) + (10 - 2) + (8 - 6) = 3 + 8 + 2 = 13.

对于Figure 2:总花费为= (8 - 2) + (6 - 5) + (10 - 2) = 6 + 1 + 8 = 15.

对于Figure 3:总花费为= (8 - 5) + 0 + (3 - 2) = 3 + 0 + 1 = 4.

此时第三种方案的总花费是最小的

 

解题思路:首先,我们当然需要对这n个数进行下排序,然后再计算出每连个数之间的差值,再对这些差值进行排序,去掉最大的m-1个差值就行了,然后我们怎么算它的花费呢?

其实我们可以发现最大值-最小值的差值是可以通过每两个数的差值加起来就是总的了,也就是说总共n-1个差值,去掉了m-1个差值,把剩下n-m个差值累加起来就是答案了。

附上代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int inf=0x3f3f3f3f;
int n,m;
int a[105],b[105];

int main()
{
    int t;
    cin>>t;
    int count=0;
    while(t--)
    {
        count++;
        int sum=0;
        cin>>n>>m;
        for(int i=1;i<=n;i++)
        cin>>a[i];
        sort(a+1,a+n+1);
        for(int i=1;i<=n-1;i++) b[i]=a[i+1]-a[i];
        sort(b+1,b+n);
        for(int i=1;i<=n-m;i++) sum+=b[i];
        printf("Case #%d: %d
",count,sum);
    }
    return 0;
 } 
/* 
4
8 3
5 2 3 10 7 2 6 8
5 5
10 1 29 15 6
4 1
105 3 27 86
10 2
37 290 15 60 4 39 2 8 275 301
*/

 

原文地址:https://www.cnblogs.com/zjl192628928/p/9391406.html