hdoj1412搬寝室
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int n, k;
int w[2000], p[2000][1000]; //w重量,p[i][j]前i个物品中搬j个的最小体力
int main()
{
while (scanf("%d%d", &n, &k) != EOF) {
for (int i = 1; i <= n; ++i)
scanf("%d", w + i);
for (int i = 1; i < n; ++i) //从小到大排序
for (int j = n - 1; j >= i; --j)
if (w[j] > w[j + 1])
swap(w[j], w[j + 1]);
for (int i = 0; i <= n; ++i) //初始化
p[i][0] = 0;
for (int i = 1; i <= k; ++i) //下面会用到的临界值
p[2 * i - 1][i] = 1000000000; //赋值无穷大,这种不可能的情况就不会被选择
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= i / 2; ++j) {
p[i][j] =
min(p[i - 2][j - 1] +
(w[i] - w[i - 1]) * (w[i] - w[i - 1]),
p[i - 1][j]);
}
}
printf("%d\n", p[n][k]);
}
}
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int n, k;
int w[2000], p[2000][1000]; //w重量,p[i][j]前i个物品中搬j个的最小体力
int main()
{
while (scanf("%d%d", &n, &k) != EOF) {
for (int i = 1; i <= n; ++i)
scanf("%d", w + i);
for (int i = 1; i < n; ++i) //从小到大排序
for (int j = n - 1; j >= i; --j)
if (w[j] > w[j + 1])
swap(w[j], w[j + 1]);
for (int i = 0; i <= n; ++i) //初始化
p[i][0] = 0;
for (int i = 1; i <= k; ++i) //下面会用到的临界值
p[2 * i - 1][i] = 1000000000; //赋值无穷大,这种不可能的情况就不会被选择
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= i / 2; ++j) {
p[i][j] =
min(p[i - 2][j - 1] +
(w[i] - w[i - 1]) * (w[i] - w[i - 1]),
p[i - 1][j]);
}
}
printf("%d\n", p[n][k]);
}
}