Problem 1603 - Minimum Sum 【数学】

题目链接:Problem 1603 - Minimum Sum

Problem 1603 - Minimum Sum Time Limit: 2000MS Memory Limit: 65536KB
Total Submit: 567 Accepted: 160 Special Judge: No DescriptionThere 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.
InputThere 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.OutputFor each test case, output minimum Sum in a line.Sample Input4 2
5 1 7 10
5 3
1 8 6 3 10Sample Output2
8

题意:就是选择一个B序列使得和最小。

说的很吓人,其实很水。我们不用考虑它们的顺序,因为你选任意m个数总是合法的。那么直接sort下。然后枚举连续的非降序区间[l, r],统计的贡献就是 ri=lij=l(a[i]a[j]) 。显然有公式可用。。。

AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <vector>
#define fi first
#define se second
#define ll o<<1
#define rr o<<1|1
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int MOD = 1e9 + 7;
const int MAXN = 1e6 + 10;
const int INF = 1e9 + 10;
void add(LL &x, LL y) { x += y; x %= MOD; }
int a[MAXN], b[MAXN];
LL sum[MAXN], ssum[MAXN];
LL Solve(int l, int r, int m) {
    return (sum[r] - sum[l-1]) * m - (ssum[r-1] - ssum[l-1] - (m-1) * sum[l-1]) - ((ssum[r] - ssum[l-1]) - m * sum[l-1]);
}
int main()
{
    int n, m;
    while(scanf("%d%d", &n, &m) != EOF) {
        for(int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            b[i] = a[i];
        }
        sort(b+1, b+n+1); sum[0] = 0;
        for(int i = 1; i <= n; i++) {
            sum[i] = sum[i-1] + b[i];
        }
        ssum[0] = 0;
        for(int i = 1; i <= n; i++) {
            ssum[i] = ssum[i-1] + sum[i];
        }
        LL ans = INF;
        for(int i = 1; i <= n; i++) {
            int j = i + m - 1;
            if(j > n) break;
            ans = min(ans, Solve(i, j, m));
        }
        printf("%lld\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值