The problem of stone merging consists of straight and round shapes:
Straight Type:
The linear lion merge problem has the following recursion:
F[I][J]: The minimum cost of merging from the first heap to the bottom of the J heap
f[i][j]=0; I=j
F[i][j]=min (F[i][k]+f[k+1][j]+sum (i,j)); i<=k<j;
This problem is better understood, according to the recursive, our I to go from high to the end, j to traverse from low to high
The line code is as follows:
#include <iostream> #include <vector>using namespace std;int sum (vector<int> &stone,int l,int R) { int res=0; for (int i=l;i<=r;i++) {res+=stone[i]; } return res; int merge (vector<int> &stone) {int res=0; int f[100][100]={0}; int len=stone.size (); for (int i=0;i<len;i++) {f[i][i]=0; } for (int i=len-2;i>=0;i--) {for (int j=i+1;j<len;j++) { int M=int_max; for (int k=i;k<j;k++) {if (M>f[i][k]+f[k+1][j]+sum (STONE,I,J) ) {m=f[i][k]+f[k+1][j]+sum (stone,i,j); }} f[i][j]=m; }} return f[0][len-1];} int main () {int n=0; Vector<int> Stone; while (cin>>n) {stone.clear (); int a=0; for (int i=0;i<n;i++) {cin>>a; Stone.push_back (a); } cout<<merge (Stone) <<endl; } return 0;}
Algorithm to review the problem of stone merging in dynamic programming