hdu1421 搬寝室
http://acm.hdu.edu.cn/showproblem.php?pid=1421
DP
dfs记忆化搜索写的,没空间优化
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define N 2013 5 6 int n, k, a[N], dp[N][N]; 7 8 int min(int x, int y) 9 { 10 return x<y? x: y; 11 } 12 13 int sq(int x) 14 { 15 return x*x; 16 } 17 18 int dfs(int i, int j) 19 { 20 if(~dp[i][j]) 21 { 22 return dp[i][j]; 23 } 24 if(i == j) 25 { 26 dp[i][j] = dfs(i-2, j-2)+sq(a[i-1]-a[i]); 27 return dp[i][j]; 28 } 29 dp[i][j] = min(dfs(i-2, j-2)+sq(a[i-1]-a[i]), dfs(i-1, j)); 30 return dp[i][j]; 31 } 32 33 int cmp(const void *a, const void *b) 34 { 35 return *((int *)a) - *((int *)b); 36 } 37 38 int main() 39 { 40 int i, j; 41 while(~scanf("%d%d", &n, &k)) 42 { 43 k <<= 1; 44 for(i=1; i<=n; i++) 45 { 46 scanf("%d", a+i); 47 } 48 qsort(a+1, n, sizeof(a[0]), cmp); 49 dp[0][0] = 0; 50 for(i=1; i<=n; i++) 51 { 52 dp[i][0] = 0; 53 for(j=2; j<=i; j+=2) 54 { 55 dp[i][j] = -1; 56 } 57 } 58 printf("%d\n", dfs(n, k)); 59 } 60 return 0; 61 }