• C++背包示例


    /*
    *   description:背包示例
    *               一个大小为17的背包,有5类不同大小与价值的物品,求使得背包中的物品价值最大的组合
    *               item    A    B    C    D    E
    *               size    3    4    7    8    9
    *               value    4    5    10    11    13
    *
    *   writeby:    nick
    *   date:       2012-10-22 23:56
    */
    #include <iostream>
    #include <string.h>
    #define N 5
    using namespace std;
    
    typedef struct
    {
        int size; int val;
    } Item;
    
    Item items[5]={{3,4},{4,5},{7,10},{8,11},{9,13} };
    
    int knap(int cap)
    {
        int i,space,max,t;
        max = 0;
        for(i=0; i<N; i++)
        {
            if((space = cap-items[i].size) >=0 )
                if((t=knap(space) + items[i].val)>max)
                    max = t;
        }
        return max;
    }
    
    int main()
    {
        cout << knap(17);
        return 0;
    }

    改进后:

    /*
    *   description:背包示例
    *               一个大小为17的背包,有5类不同大小与价值的物品,求使得背包中的物品价值最大的组合
    *               item    A    B    C    D    E
    *               size    3    4    7    8    9
    *               value    4    5    10    11    13
    *
    *   writeby:    nick
    *   date:       2012-10-22 23:56
    */
    #include <iostream>
    #include <string.h>
    #define N 5   //物品个数
    #define M 17  //容量
    
    using namespace std;
    
    typedef struct
    {
        int size; int val;
    } Item;
    
    Item items[5]={{3,4},{4,5},{7,10},{8,11},{9,13} };
    int maxKnown[M] = {0};
    
    int knap(int cap)
    {
        int space,max,t;
        if(maxKnown[cap] != 0 ) return maxKnown[cap];
    
        max = 0;
        for(int i=0; i<N; i++)
        {
            if((space = cap-items[i].size) >=0 )
                if((t=knap(space) + items[i].val)>max)
                {
                    max = t;
                }
        }
        maxKnown[cap] = max;
        return max;
    }
    
    int main()
    {
        memset(maxKnown, 0, sizeof(maxKnown));
        cout << knap(M);
        return 0;
    }

    方法:

    1. 使用递归

    2. for遍历每个物品,求出空量space,使用该space递归求出最大值value,如果value+items[i].value>max,修改max的值

    3. 返回max

    改进: 用静态数组保存对应space的max值。

  • 相关阅读:
    计算机网络
    计算机网络
    Spring Boot自定义参数不提示、@ConfigurationProperties报错
    计算机网络概述
    面试题:类的初始化与实例的初始化
    面试题:自增变量
    最近做了一个Spring Boot小项目,大家帮忙找找bug吧, http://www.dbeetle.cn
    设计模式
    6.7 使用show profile 进行sql分析
    6.6 构建大表
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2734915.html
Copyright © 2020-2023  润新知