样例输入
3
1 1 3
5 6 10
2 1 2
1 1 1 50
1 1
5 6
2 1
样例输出
50
典型的DP最优填表是二维数组,行表示阶段,列表示状态,继而表格内数据即为该阶段该状态下的最优值。该题每一阶段需要用二维数组表示,每遍历完一个状态就对数组更新一次,这样数组内始终是当前状态下的最优值。
#include
using namespace std;
#define NUM 501
int trade[NUM][NUM],carry[NUM][NUM];
int min(int x,int y)
{
if(x>y) return y;
else return x;
}
void main()
{
int w[4],s[4],d[4],i,n;
cin>>n;
for(i=1;i<=3;i++)
cin>>w[i]>>s[i]>>d[i];
int c1,c2,c3,d4;
cin>>c1>>c2>>c3>>d4;
d4-=c1*d[1]+c2*d[2]+c3*d[3];
memset(carry,-1,sizeof(carry));
carry[0][0]=0; //初始化什么都不装
int row=0,col=0,j,k,ja,ka;
for(i=0;i
{
int weight,size;
cin>>weight>>size;
memset(trade,-1,sizeof(trade));
int newrow=row,newcol=col; //追踪有效地行数和列数,只对有效地行列操作
int weight1,size1,weight2,size2;
for(j=0;j<=row;j++)
for(k=0;k<=col;k++)
if(carry[j][k]>=0) //原来存在该种装备组合情况,在该组合基础上对当前马车运载组合进行枚举
for(ja=j,weight1=size1=0;(weight1<=weight&&size1<=size);weight1+=w[1],size1+=s[1],ja++)
for(ka=k,weight2=weight1,size2=size1;(weight2<=weight&&size2<=size);weight2+=w[2],size2+=s[2],ka++)
{
if(newrow
if(newcol
int bootweight=(weight-weight2)/w[3];
int bootsize=(size-size2)/s[3];
if(bootweight>bootsize)
bootweight=bootsize;
bootweight+=carry[j][k];
if(trade[ja][ka]
trade[ja][ka]=bootweight;
}
memcpy(carry,trade,sizeof(trade));
row=newrow;
col=newcol;
}
int ibest=0; //搜索carry[j][k]获得最优值
for(j=0;j<=row;j++)
for(k=0;k<=col;k++)
if(carry[j][k]>=0)
{
int defend=j*d[1]+k*d[2]+carry[j][k]*d[3];
int helms=j/c1;
int armors=k/c2;
int boots=carry[j][k]/c3;
if(d4>0)
defend+=d4*min(helms,min(armors,boots));
if(ibest
ibest=defend;
}
cout<
}