two simple problems solved by dynamic programming

来源:互联网 发布:网贷大数据免费查询 编辑:程序博客网 时间:2024/05/22 10:54

Hello,everyone.I said i will spend three days to learn the dynamic programming.And today is the first day.I will show two simple problems solved by dynamic programming.And there is on doubt that if you want  to understand and use it well,you have to practice again and again.

Have fun coding,i_human.Have fun coding,everyone!


THE CODE:


// 数字三角问题.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include<iostream>
#define a1 100


using namespace std;


int find(int a,int b);


int c[a1][a1];
int d[a1][a1];
int n;


int main()
{
cin>>n;
for(int i=0;i<a1;i++)
for(int j=0;j<a1;j++)
d[i][j]=-1;
for(int i=0;i<n;i++)
for(int j=0;j<=i;j++)
cin>>c[i][j];
cout<<find(0,0);
system("pause");
return 0;
}


int find(int a,int b)
{
if(d[a][b]!=-1)
return d[a][b];
if(a==n-1)
{
d[a][b]=c[a][b];
return d[a][b];
}
if(find(a+1,b)>find(a+1,b+1))
{
d[a][b]=c[a][b]+d[a+1][b];
return d[a][b];
}
if(find(a+1,b)<=find(a+1,b+1))
{
d[a][b]=d[a+1][b+1]+c[a][b];
return d[a][b];
}
}


// 矩阵连乘问题.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include<iostream>
#define a1 100


using namespace std;


int c[2][a1];
int f[a1][a1];


int cal(int a,int b);


int main()
{
int n;
cin>>n;
for(int j=0;j<a1;j++)
for(int k=0;k<a1;k++)
f[j][k]=-1;
for(int i=1;i<=n;i++)
cin>>c[0][i]>>c[1][i];
cout<<cal(1,n)<<endl;
system("pause");
return 0;
}


int cal(int a,int b)
{
int d=1000000;
int e;
if(f[a][b]!=-1)
return f[a][b];
if(a==b)
return 0;
if(b>a)
{
for(int l=a;l<b;l++)
{
e=cal(a,l)+cal(l+1,b)+c[0][a]*c[1][l]*c[1][b];
if(e<=d)
d=e;
}
f[a][b]=d;
return d;
}
if(b<a)
{
cout<<"error"<<endl;
return 0;
}
}

0 0
原创粉丝点击