P1040 加分二叉树 —— 树的遍历与区间dp引申

P1040 加分二叉树 —— 树的遍历与区间dp引申_第1张图片

P1040 加分二叉树 —— 树的遍历与区间dp引申_第2张图片

import java.util.Scanner;

public class Main {
    static int[] value = new int[35];
    static int[][] dp = new int[35][35];
    static int[][] root = new int[35][35];

    //按照先序遍历输出
    static void dfs(int left, int right) {
        if (left <= right) {
            System.out.print(root[left][right] + " ");
            dfs(left, root[left][right] - 1);
            dfs(root[left][right] + 1, right);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                dp[i][j] = 1;
            }
        }
        for (int i = 1; i <= n; i++) {
            value[i] = sc.nextInt();
            dp[i][i] = value[i];
            root[i][i] = i;
        }

        //区间dp
        for (int len = 1; len < n; len++) {
            for (int i = 1; i <= n; i++) {
                int j = i + len;
                for (int k = i; k <= j; k++) {
                    if (dp[i][k - 1] * dp[k + 1][j] + dp[k][k] > dp[i][j]) {
                        dp[i][j] = dp[i][k - 1] * dp[k + 1][j] + dp[k][k];
                        root[i][j] = k;
                    }
                }
            }
        }
        System.out.println(dp[1][n]);
        dfs(1, n);
    }
}


备忘:日后详更思路。(最近真的时间不够用aaaa,forgive me.)

你可能感兴趣的:(区间dp,Algorithms,DFS,经典问题)