完全背包,不过需要注意是最少H磅,也就是可能出现大于H的情况。
比如
2 15
2 2
2 3
在体积为15时,dp无法到达。
所以需要一下H的上限来解决。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int h,n,dp[1000005],w,c; int main(){ memset(dp,0x3f3f3f3f,sizeof(dp)); dp[0]=0; scanf("%d%d",&n,&h); for(int i=1;i<=n;i++){ scanf("%d%d",&w,&c); //h+h随便取的 目的是扩容 for(int j=0;j<=h+h;j++){ dp[j+w] = min(dp[j]+c,dp[j+w]); } } int Out = 0x3f3f3f3f; //记录h-2h之间的最小值 for(int i=h;i<=h+h;i++) Out = min(Out,dp[i]); printf("%d\n",Out); return 0; }