01背包(递推)

#include <iostream>
 #include <cstdio>
 
using namespace std;
const int maxn = 1000;
int v[maxn];
int w[maxn];
int n = 0, W1= 0;
int F[maxn][maxn];
 
int DP() {
     for (int i = n-1; i >= 0; i--) {
         for (int j = 0; j <= W1; j++) {
             if (w[i] > j) {
                 F[i][j] = F[i+1][j];
             }
             else {
                 F[i][j] = max(F[i+1][j], F[i+1][j-w[i]]+v[i]);
             }
         }
     }
     printf("%d\n", F[0][W1]);
     return 0;
 }
 
int init() {
     memset(F, 0, sizeof(int)*maxn*maxn);
     return 0;
 }
 
int main() {
     int m;
     scanf("%d", &m);
     for(int k = 0; k < m; k++){
     init();
         scanf("%d%d", &n, &W1);
         for (int i = 0; i < n; i++) {
             scanf("%d", &v[i]);
         }
         for (int i = 0; i < n; i++) {
             scanf("%d", &w[i]);
         }
         DP();
         init();
     }
     return 0;
 }


 

你可能感兴趣的:(01背包(递推))