变量

题目大意

给定 \(n\) 个整数常数 \(c_1,c_2,…,c_n\) 和一个整数 \(k\)。现在需要给 \(2k\) 个整数变量 \(x_1,x_2,…,x_k,y_1,y_2,…,y_k\) 赋值,满足

对于所有 \(1\le i\le k\), 都有 \(x_i\le y_i\)。对于所有 \(1≤i≤n\),都存在至少一个 \(j(1≤j≤k)\), 使得 \(x_j≤c_i≤y_j\)

求出 \((y_1+y_2+…+y_k)−(x_1+x_2+…+x_k)\) 的最小值。

题目分析

一道不错的转换型题目。

我们不妨将 \(c_i\) 看成数轴上的一些点,把 \(x_i,y_i\) 看成一条线段。

题目转换为:有一个数轴,数轴上有 \(n\) 个点和 \(k\) 条线段,每个点都被至少一条线段覆盖。最小化这些线段的长度之和。

一眼看过去当然是当每条线段都退化成一个点时最优,但这仅适用于 \(n\le k\) 的情况。

对于更为普遍的情况,先将这 \(n\) 个点从小到大排序,\(\forall i\in[1,n-1],sub_i=a_{i+1}-a_i\)\(sub_i\) 就是 \(i,i+1\) 之间的距离。再将这些距离从小到大排序,答案就是前 \(n-k\) 个距离之和。

代码

#include <iostream>
#include <cstdio>
#include <climits>//need "INT_MAX","INT_MIN"
#include <cstring>//need "memset"
#include <numeric>
#include <algorithm>
#include <cmath>
#define enter putchar(10)
#define debug(c,que) std::cerr << #c << " = " << c << que
#define cek(c) puts(c)
#define blow(arr,st,ed,w) for(register int i = (st);i <= (ed); ++ i) std::cout << arr[i] << w;
#define speed_up() std::ios::sync_with_stdio(false),std::cin.tie(0),std::cout.tie(0)
#define mst(a,k) memset(a,k,sizeof(a))
#define stop return(0)
const int mod = 1e9 + 7;
inline int MOD(int x) {
	if(x < 0) x += mod;
	return x % mod;
}
namespace Newstd {
	char buf[1 << 21],*p1 = buf,*p2 = buf;
	inline int getc() {
		return p1 == p2 && (p2 = (p1 = buf) + fread(buf,1,1 << 21,stdin),p1 == p2) ? EOF : *p1 ++;
	}
	inline int read() {
		int ret = 0,f = 0;char ch = getc();
		while (!isdigit(ch)) {
			if(ch == '-') f = 1;
			ch = getc();
		}
		while (isdigit(ch)) {
			ret = (ret << 3) + (ret << 1) + ch - 48;
			ch = getc();
		}
		return f ? -ret : ret;
	}
	inline double double_read() {
		long long ret = 0,w = 1,aft = 0,dot = 0,num = 0;
		char ch = getc();
		while (!isdigit(ch)) {
			if (ch == '-') w = -1;
			ch = getc();
		}
		while (isdigit(ch) || ch == '.') {
			if (ch == '.') {
				dot = 1;
			} else if (dot == 0) {
				ret = (ret << 3) + (ret << 1) + ch - 48;
			} else {
				aft = (aft << 3) + (aft << 1) + ch - '0';
				num ++;
			}
			ch = getc();
		}
		return (pow(0.1,num) * aft + ret) * w;
	}
	inline void write(int x) {
		if(x < 0) {
			putchar('-');
			x = -x;
		}
		if(x > 9) write(x / 10);
		putchar(x % 10 + '0');
	}
}
using namespace Newstd;

const int N = 1e5 + 5;
int a[N],sub[N];
int n,m;
int main(void) {
	n = read(),m = read();
	for (register int i = 1;i <= n; ++ i) a[i] = read();
	std::sort(a + 1,a + n + 1);
	for (register int i = 1;i < n; ++ i) sub[i] = a[i + 1] - a[i];
	std::sort(sub + 1,sub + n);
	long long ans = 0;
	for (register int i = 1;i <= n - m; ++ i) ans += sub[i];
	printf("%lld\n",ans);
	
	return 0;
}
posted @ 2022-06-18 23:58  Coros_Trusds  阅读(17)  评论(0编辑  收藏  举报