洛谷 P1060 开心的金明

Ver1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<deque>
#include<map>
#include<cstring>
using namespace std;
int n, m;
int v[30],w[30];//乘积,价格
int f[30][30005]; //物品,钱数
int main() {
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int tmp2;
        cin >> w[i] >> tmp2;
        v[i] = w[i] * tmp2;
    }
    for (int i = 1; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if(j>=w[i])f[i][j] = max(f[i - 1][j], f[i - 1][j - w[i]] + v[i]);
            else f[i][j] = f[i - 1][j];
        }
    }
    int mmax = 0;
    for (int i = 0; i <= n; i++) {
        mmax = max(mmax, f[m][i]);
    }
    cout << mmax;
}

Ver2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<deque>
#include<map>
#include<cstring>
using namespace std;
int n, m;
int v[30],w[30];//乘积,价格
int f[30005]; //钱数
int main() {
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int tmp2;
        cin >> w[i] >> tmp2;
        v[i] = w[i] * tmp2;
    }
    for (int i = 1; i <= m; i++) {
        for (int j = n; j >=w[i]; j--) {
            f[j] = max(f[j], f[j - w[i]] + v[i]);
        }
    }
    int mmax=0;
    for (int i = 0; i <= n; i++) {
        mmax = max(mmax, f[i]);
    }
    cout << mmax;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注