Solution to a problem T79222] [gem bracelet

Gemstone Bracelets

Please carefully analyze the topic, to be honest, this question is not difficult, is probably universal - the difficulty
ado, with the view to the bar


First of all, we see the first topic is how to feel? This title should feel it is a backpack, look at,
because Bessie each gem is only one, so it isfamousThe 01 backpack .
That problem is simple,
the state transition equation 01 backpack and the core code:
follows ↓↓↓
1. no optimization:

\(dp[i][j] = max( dp[i−1][j−w[i]] + c[i ], dp[i][j])\)

for(int i=1; i<=n; i++)
        for(int j=m; j>=c[i]; j--) dp[i][j] = max(dp[i-1][j-c[i]] + w[i] , dp[i][j]) ;

2. A one-dimensional array optimization

\(dp[j] = max( dp[j−w[i]] + c[i] , dp[j])\)

for(int i=1; i<=n; i++)
    for(int j=m; j>=c[i]; j--) dp[j] = max(dp[j-c[i]] + w[i] , dp[j]) ;

In this problem, \ (m \) i.e. the maximum capacity of the backpack, \ (n-\) is the number of goods items, \ (W_i, C_i \) are the weight of the article, value;
derived \ (the AC \) Code:

#include<bits/stdc++.h>
using namespace std;
int v,n,w[220005],f[220005],c[220005],ans;
int read() //快读(QuickRead)
{
     int x=0,f=1;char ch=getchar();
     while(ch<'0'||ch>'9') {if(ch=='-') f=-1; ch=getchar();}
     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
     return x*f;
}
int main()
{
    n=read();
    v=read();
    for(int i=1;i<=n;i++)
    {
        w[i]=read();
        c[i]=read();
    }
    for(int i=1;i<=n;i++)           
     for(int j=v;j>=w[i];j--)
        f[j]=max(f[j],f[j-w[i]]+c[i]);
    cout<<f[v];
}

Where \ (49-51 \) as the core code.
So, this question would happy \ (AC \) a \ (! \)

\ (Qaq \)

Guess you like

Origin www.cnblogs.com/Luke-Skywalker/p/11227601.html