hdu1421搬寝室dp

状态转移方程

if (j==2*i+1) {
  dp[j][i] = dp[j-2][i-1]+ (val[j]-val[j-1])*(val[j]-val[j-1]);
}else {
  dp[j][i] = Math.min(dp[j-1][i], dp[j-2][i-1]+ (val[j]-val[j-1])*(val[j]-val[j-1]));
}

 

import java.util.Arrays;
import java.util.Scanner;

public class hdu1421 {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int k = sc.nextInt();
            int[] val = new int[n];
            int[][] dp = new int[n][k];
            for (int i = 0; i < val.length; i++) {
                val[i] = sc.nextInt();            
            }
            Arrays.sort(val);
            dp[0][0] = 0;
            dp[1][0] = (val[1]-val[0])*(val[1]-val[0]);
            for (int j = 2; j < dp.length; j++) {
                dp[j][0] = Math.min(dp[j-1][0], (val[j]-val[j-1])*(val[j]-val[j-1]));            
            }
            
            for (int i = 1; i < k; i++) {
                for (int j = 2*i+1; j < n; j++) {
                    if (j==2*i+1) {
                        dp[j][i] =  dp[j-2][i-1]+ (val[j]-val[j-1])*(val[j]-val[j-1]);
                    }else {
                        dp[j][i] = Math.min(dp[j-1][i], dp[j-2][i-1]+ (val[j]-val[j-1])*(val[j]-val[j-1]));
                    }                
                }
            }
            System.out.println(dp[n-1][k-1]);
        }
        sc.close();
    }

}

 

posted @ 2024-06-15 21:46  XiaohuangTX  阅读(2)  评论(0编辑  收藏  举报