Algorithm to review the problem of stone merging in dynamic programming

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.