Description
有N 个人要参加国际象棋比赛,该比赛要进行K场对弈。
每个人最多参加两场对弈,最少参加零场对弈。每个人都有一个与其他人都不相同的等级(用一个正整数来表示)。
在对弈中,等级高的人必须用黑色的棋子,等级低的人必须用白色的棋子。
每一个人最多只能用一次黑色的棋子和一次白色的棋子。
为了增加比赛的可观度,观众希望K场对弈中双方的等级差的总和最小。
比如有7个选手,他们的等级分别是30, 17, 26, 41, 19, 38, 18要进行3场比赛。最好的安排是Player 2 vs Player 7, Player7 vs Player 5 , Player 6 vs Player 4,此时等级差的总和等于(18-17) + (19-18) + (41-38) = 5达到最小。
Input
第一行两个正整数N ,K。
接下来有N 行,第i行表示第i . 1个人等级。
Output
在第一行输出最小的等级差的总和。
Analysis
典型贪心。
扫描二维码关注公众号,回复:
2206202 查看本文章
Implementation
自行脑补。
Code
C++
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n, k, d[100005], x[100005];
bool cmp(int x, int y)
{
return x > y;
}
int main(int argc, char const *argv[])
{
freopen("init.in", "r", stdin);
//freopen("chess.out","w",stdout);
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i++)
scanf("%d", &d[i]);
sort(d + 1, d + n + 1, cmp);
for (int i = 1; i <= n - 1; i++)
x[i] = d[i] - d[i + 1];
sort(x + 1, x + n);
int ans = 0;
for (int i = 1; i <= k; i++)
ans += x[i];
printf("%d\n", ans);
return 0;
}
Pascal
自行脑补