题目:http://acm.hdu.edu.cn/showproblem.php?pid=3480
#include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> #define ll long long #define clr(a,b) memset(a, b, sizeof(a)) using namespace std; const int N = 10000+10; const int M = 10000+10; const int inf = 0x3f3f3f3f; int m, n; int a[N], dp[N/2][N], s[N/2][N]; // dp[i][j] = min{dp[i-1][k] + sqr(a[j]-a[k+1])}, 0<k<j void input() { scanf("%d%d", &n, &m); for (int i=1; i<=n; i++) scanf("%d", &a[i]); sort(a+1, a+1+n); } int main() { //freopen("D:/a.txt", "r", stdin); int T, cas=1; scanf("%d", &T); while (T--) { input(); for (int j=1; j<=n; j++) s[1][j]=0, dp[1][j]=(a[j]-a[1])*(a[j]-a[1]); for (int i=2; i<=m; i++) { for (int j=n; j>=i; j--) { dp[i][j] = inf; int st = s[i-1][j], ed = s[i][j+1]; if (j==n) st=i-1, ed=n; for (int k=st; k<=ed; k++) { int tmp = (a[j]-a[k+1])*(a[j]-a[k+1]); if (dp[i][j] > dp[i-1][k] + tmp) s[i][j] = k, dp[i][j] = dp[i-1][k] + tmp; } } } printf("Case %d: %d\n", cas++, dp[m][n]); } return 0; }