0-1揹包与完全揹包 SDNUOJ1033采药(一维数组)1043采药2(一维数组)

1033(一维数组)(揹包容量 j 逆序枚举)0-1揹包

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define N 1005
int v[N],w[N];
int m[N];

int main()
{
    int c, n;
    while(cin >> c >> n)
    {
        for(int i = 1; i <= n; i++)
        {
            cin >> w[i] >> v[i];
        }
        memset(m, 0, sizeof(m));
        for(int i = 1; i <= n; i++)
        {
            for(int j = c; j >= w[i]; j--)
            {
                m[j] = max(m[j],m[j-w[i]] + v[i]);
            }
        }
        cout << m[c] << endl;
    }
    return 0;
}

1043(揹包容量 j 顺序枚举)完全揹包

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define N 1005
int v[N],w[N];
int m[N];

int main()
{
    int c, n;
    while(cin >> c >> n)
    {
        for(int i = 1; i <= n; i++)
        {
            cin >> w[i] >> v[i];
        }
        memset(m, 0, sizeof(m));
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= c; j++)
            {
                if(j >= w[i])
                    m[j] = max(m[j],m[j-w[i]] + v[i]);
                else
                    m[j] = m[j - 1];
            }
        }
        cout << m[c] << endl;
    }
    return 0;
}

点赞