例题:https://www.acwing.com/problem/content/284/
简易描述:有N堆石子,将N堆石子合并成一堆,只能合并相邻两堆石子,选择的总代价为两堆石子总和。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #include<bits/stdc++.h> using namespace std; const int N =305; int pre[N]; int dp[N][N]; int n; const int inf =INT_MAX/2; int main(void) { cin>>n; for(int i=1;i<=n;i++) cin>>pre[i], pre[i] +=pre[i-1]; for(int len=2;len<=n;len++) { for(int i=1;i+len-1<=n;i++) { int j =i+len-1; dp[i][j] = inf; for(int k=i;k<=j;k++) { dp[i][j] =min(dp[i][j],dp[i][k]+dp[k+1][j]+pre[j]-pre[i-1]); } } } cout<<dp[1][n]<<endl; }
|