原文链接:https://www.luogu.com.cn/problem/P1509
01背包的变形,建立二维数组,双dp
AC代码:
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
int n,m,r,rmb[105],rp[105],tim[105],dp[105][105],dp1[105][105];
int main(){
int i,j,k;
memset(dp,0,sizeof(dp));
memset(dp1,0,sizeof(dp1));
cin>>n;
for(i=1;i<=n;i++){
cin>>rmb[i]>>rp[i]>>tim[i];
}
cin>>m>>r;
for(i=1;i<=n;i++){
for(j=m;j>=rmb[i];j--){
for(k=r;k>=rp[i];k--){
if(dp[j][k]<dp[j-rmb[i]][k-rp[i]]+1){
dp[j][k]=max(dp[j][k],dp[j-rmb[i]][k-rp[i]]+1);
dp1[j][k]=dp1[j-rmb[i]][k-rp[i]]+tim[i];
}
else if(dp[j][k]==dp[j-rmb[i]][k-rp[i]]+1){
dp1[j][k]=min(dp1[j][k],dp1[j-rmb[i]][k-rp[i]]+tim[i]);
}
}
}
}
cout<<dp1[m][r]<<endl;
return 0;
}