1130. 叶值的最小代价生成树
Posted zouma
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1130. 叶值的最小代价生成树相关的知识,希望对你有一定的参考价值。
1.dp
1 int mctFromLeafValues(vector<int>& arr) { 2 int len = arr.size(); 3 vector<vector<int>> rmq(len, vector<int>(len, 0)); 4 for (int i = 0; i < len; i++) 5 rmq[i][0] = arr[i]; 6 for (int j = 1; (1<<j)<len ; j++) 7 { 8 for (int i = 0; i+(1<<j-1)<len ; i++) 9 { 10 rmq[i][j] = max(rmq[i][j - 1], rmq[i + (1 << j - 1)][j - 1]); 11 } 12 } 13 vector<vector<int>> dp(len, vector<int>(len, INT_MAX)); 14 for (int i = 0; i < len; i++) 15 dp[i][i] = 0; 16 for (int i = 1; i < len; i++) 17 { 18 for (int j = 0; j < len - i; j++) 19 { 20 for (int k = j; k < i + j; k++) 21 { 22 int width1 = log2(k - j + 1); 23 int width2 = log2(j + i - k); 24 dp[j][j + i] = min(dp[j][j + i], dp[j][k] + dp[k + 1][j + i] + max(rmq[j][width1],rmq[k-(1<<width1)+1][width1])*max(rmq[k+1][width2],rmq[j+i-(1<<width2)+1][width2])); 25 } 26 } 27 } 28 return dp[0][len - 1]; 29 }
以上是关于1130. 叶值的最小代价生成树的主要内容,如果未能解决你的问题,请参考以下文章