1 solutions

  • 0
    @ 2023-3-1 21:07:18

    i为当前遍历到的物品编号,j为背包容量。 分能放和不能放两种情况

    状态转移方程:

    //如果能放
    dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+p[i]);
    //如果不能放
    dp[i][j]=dp[i-1][j];
    
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    int dp[128][20002];
    int maxw,n,caw=0,cap=0;
    int w[128],p[128];
    int main()
    {
    	memset(dp,0,sizeof(dp));
    	cin>>maxw>>n;
    	for(int i=1;i<=n;i++)
    	{
    		cin>>w[i]>>p[i];
    		for(int j=1;j<=maxw;j++)
    		{
    			if(w[i]<=j)
    			{
    				dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+p[i]);
    			}
    			else
    			{
    				dp[i][j]=dp[i-1][j];
    			}
    		}
    	}
    	cout<<dp[n][maxw];
    }
    

    Information

    ID
    620
    Time
    1000ms
    Memory
    64MiB
    Difficulty
    8
    Tags
    # Submissions
    97
    Accepted
    18
    Uploaded By