背包问题c++动态规划方式

#include <iostream>
using namespace std;

int weight[5] = {5,2,4,8,6};
int len[5] = {2,4,3,1,7};
int num = 5;
int space = 15;

int main() {
        int max_weight[15] = {0};
        for(uint32_t i=0; i<num;i++) {
                for(uint32_t j=space; j>len[i]; j--) {
                        if (max_weight[j-len[i]] + weight[i] > max_weight[j]) {
                                max_weight[j] = max_weight[j-len[i]] + weight[i];
                        }
                }
                for(uint32_t j=0; j<space; j++) {
                        cout<<max_weight[j]<<" ";
                }
                cout<<endl;

        }
        cout<<max_weight[14]<<endl;
        return 0;
}

  结果

0 0 0 5 5 5 5 5 5 5 5 5 5 5 5
0 0 0 5 5 5 5 7 7 7 7 7 7 7 7
0 0 0 5 5 5 9 9 9 9 11 11 11 11 11
0 0 8 8 13 13 13 17 17 17 17 19 19 19 19
0 0 8 8 13 13 13 17 17 17 17 19 19 19 23
23

  

猜你喜欢

转载自www.cnblogs.com/sailrancho/p/11781306.html
今日推荐