[luoguP1040] 加分二叉树(DP)
Posted 蒟蒻zht的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[luoguP1040] 加分二叉树(DP)相关的知识,希望对你有一定的参考价值。
区间DP水题
代码
#include <cstdio> #include <iostream> #define N 41 #define max(x, y) ((x) > (y) ? (x) : (y)) int n; int a[N], f[N][N], pre[N][N]; inline int read() { int x = 0, f = 1; char ch = getchar(); for(; !isdigit(ch); ch = getchar()) if(ch == ‘-‘) f = -1; for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - ‘0‘; return x * f; } inline void solve(int l, int r) { printf("%d ", pre[l][r]); if(l <= pre[l][r] - 1) solve(l, pre[l][r] - 1); if(pre[l][r] + 1 <= r) solve(pre[l][r] + 1, r); } int main() { int i, j, k; n = read(); for(i = 1; i <= n; i++) f[i][i] = read(), pre[i][i] = i; for(i = n; i >= 1; i--) for(j = i + 1; j <= n; j++) { if(f[i][i] + f[i + 1][j] > f[i][j]) f[i][j] = f[i][i] + f[i + 1][j], pre[i][j] = i; for(k = i + 1; k < j; k++) if(f[i][k - 1] * f[k + 1][j] + f[k][k] > f[i][j]) f[i][j] = f[i][k - 1] * f[k + 1][j] + f[k][k], pre[i][j] = k; if(f[j][j] + f[i][j - 1] > f[i][j]) f[i][j] = f[j][j] + f[i][j - 1], pre[i][j] = j; } printf("%d\n", f[1][n]); solve(1, n); return 0; }
以上是关于[luoguP1040] 加分二叉树(DP)的主要内容,如果未能解决你的问题,请参考以下文章