记录编号 349403 评测结果 AAAAAAAAAA
题目名称 社长的qwa 最终得分 100
用户昵称 Gravatarjinqiu 是否通过 通过
代码语言 C++ 运行时间 0.017 s
提交时间 2016-11-14 21:43:52 内存使用 1.08 MiB
显示代码纯文本
#include<iostream>
#include<cstdio>
#include<algorithm>
#define LL long long
using namespace std;

const LL inf = 0x7fffffffffffffff;
const int maxn = 1e5 + 10;
int n, k;
LL ans = inf;
LL a[maxn];

int main() {
	freopen("qwa.in", "r", stdin);
	freopen("qwa.out", "w", stdout);
	int i;
	cin >> n >> k;
	for(i = 1; i <= n; i++)
		scanf("%lld", a + i);
	sort(a + 1, a + 1 + n);
	LL now = 0, sum = 0;
	for(i = 1; i <= k; i++) {
		now = now + (i - 1)*a[i] - sum;
		sum += a[i];
	}
	for(i = k + 1; i <= n; i++) {
		ans = min(ans, now);
		sum -= a[i - k];
		now -= sum - a[i - k]*(k - 1);
		now += a[i]*(k - 1) - sum;
		sum += a[i];
	}
	ans = min(ans, now);
	cout << ans << "\n";
	return 0;
}