区间动态规划 scu2117 加分二叉树
题目链接:https://vjudge.net/problem/SCU-2117
#include <iostream> #include<vector> #include<algorithm> #include<string> #include<map> using namespace std; void dfs(vector<vector<int>> &front, int i,int j) { if (i > j) return; cout << front[i][j]+1 << " "; if (i == j) return; dfs(front, i, front[i][j] - 1); dfs(front, front[i][j] + 1, j); } int main() { int n; int score[30]; while (cin >> n) { for (int i = 0; i < n; i++) cin >> score[i]; vector<vector<int>> dp(n, vector<int>(n, 0)); vector<vector<int>> front(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) { dp[i][i] += score[i]; front[i][i] = i; } for (int i = 1; i < n; i++) { for (int j = 0; j + i < n; j++) { for (int k = j; k <= j + i; k++) { if (k == j) { if (dp[j][j + i] < score[j] + dp[j + 1][j + i]) { dp[j][j + i] = score[j] + dp[j + 1][j + i]; front[j][j + i] = k; } } else if (k == j + i) { if (dp[j][j + i] < score[j + i] + dp[j][j + i - 1]) { dp[j][j + i] = score[j + i] + dp[j][j + i - 1]; front[j][j + i] = k; } } else { if (dp[j][j + i] < score[k] + dp[j][k - 1] * dp[k + 1][j + i]) { dp[j][j + i] = score[k] + dp[j][k - 1] * dp[k + 1][j + i]; front[j][j + i] = k; } } } } } cout << dp[0][n - 1] << endl; dfs(front, 0, n - 1); cout << endl; } return 0; }
posted on 2020-03-09 16:15 QingFengDaHui 阅读(161) 评论(0) 编辑 收藏 举报