jzoj 1305. Chess

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Larry1118/article/details/87440723

这题我们可以用贪心来做。
我们发现对于每个人,如果他要下棋的话,只有和比它等级高的第一个和比它等级低的第一个下才是最优的!!!
所以我们可以先将等级a按从小到大排序。
然后,对于每个点对答案的贡献弄到一个数组c。
然后再将c数组按从小到大排序。
只要累加前k个,便是答案了。
上标:

#include<cstdio>
#include<algorithm>
#define N 100010
#define ll long long
using namespace std;
int n,K,a[N],gap[N];
ll ans=0;

inline int read()
{
	int x=0; char c=getchar();
	while (c<'0' || c>'9') c=getchar();
	while (c>='0' && c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
	return x;
}

int main()
{
	n=read(),K=read();
	for (int i=1;i<=n;i++) a[i]=read();
	sort(a+1,a+n+1);
	for (int i=1;i<n;i++) gap[i]=a[i+1]-a[i];
	sort(gap+1,gap+n);
	for (int i=1;i<=K;i++) ans+=gap[i];
	printf("%lld\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Larry1118/article/details/87440723