Whu oj Problem 1603 - Minimum Sum

本文介绍了一种解决特定数组问题的算法,目标是在指定数量的元素中找到和最小的组合。通过排序和动态计算,该算法有效地解决了这一挑战,适用于大规模数据集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 1603 - Minimum Sum

Time Limit: 2000MS   Memory Limit: 65536KB  
Total Submit: 541  Accepted: 147  Special Judge: No
Description

There are n numbers A[1] , A[2] .... A[n], you can select m numbers of it A[B[1]] , A[B[2]] ... A[B[m]]  ( 1 <= B[1] < B[2] .... B[m] <= n ) such that Sum as small as possible.

Sum is sum of abs( A[B[i]]-A[B[j]] ) when 1 <= i < j <= m.

Input
There are multiple test cases.
First line of each case contains two integers n and m.( 1 <= m <= n <= 100000 )
Next line contains n integers A[1] , A[2] .... A[n].( 0 <= A[i] <= 100000 )
It's guaranteed that the sum of n is not larger than 1000000.
Output
For each test case, output minimum Sum in a line.
Sample Input
4 2
5 1 7 10
5 3
1 8 6 3 10
Sample Output
2
8

开始想复杂了。先排序找到前m位的sum值,在一次向后移,其间记录最小值。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define maxn 100010
using namespace std;
int a[maxn];
int n,m;
long long fun()//求前m位的sum值
{
    int tem=m-1;
    int cnt=1;
    long long sum=0;
    for(int i=1;i<m;++i)
    {
        int dif=a[i]-a[i-1];
        sum+=dif*(tem*cnt);
        tem--;
        cnt++;
    }
    return sum;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=0;i<n;++i)
            scanf("%d",&a[i]);
        sort(a,a+n);
        long long sum=fun();
        long long ans=sum;
        int k=0;
        for(int i=m;i<n;++i)
        {
            for(int j=k+1;j<i;++j)
            {
                sum-=(a[j]-a[k]);
                sum+=(a[i]-a[j]);
            }
            ans=min(ans,sum);
            k++;
        }
        printf("%lld\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值