码迷,mamicode.com
首页 > 其他好文 > 详细

分组背包问题描述与实现

时间:2015-03-13 18:33:46      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
int w[301][21];    

int get_max(int a, int b)
{
    if(a>=b)
        return a;
    else
        return b;
}

int main(void)
{
    int tc, T;
    
    
    setbuf(stdout, NULL);
    
    int Amout = 0;
    int company_num = 0;
    int i,j,k;
    
    scanf("%d", &T);
    for(tc = 0; tc < T; tc++)
    {
        
        scanf("%d%d", &Amout, &company_num);

        for(i = 1; i <= Amout; i++)
        {
            for(j = 0; j <= company_num; j++)
                scanf("%d", &w[i][j]);        //w[i][j] :投入为i 时公司j能获得的利润。
        }

        int profit[21][301] = {0,};
        
        //分组背包问题        
        profit[1][1] = w[1][1];

        int max = profit[1][1];
        for( i = 2; i <= company_num; i++)    //amout = 1;
        {
            if (w[1][i] >max)    //w[k][i] :投入为k时公司i能获得的利润
            {
                max = w[1][i];
                profit[i][1] = w[1][i];
            }
            else
                profit[i][1] = max;            
        }

        max = profit[1][1];
        for( i = 2; i <= Amout; i++)    //company = 1;
        {            
            if (w[i][1]  > max)
            {
                max = w[i][1];
                profit[1][i] = w[i][1];
            }
            else
            {
                profit[1][i] = max;
            }            
        }

        int t;
        //开始迭代运算了
        //f[k][v] = max{ f[k-1][v], f[k-1][v-c]+w }
        for( i = 2; i <= company_num; i++)
        {            
            for(j = 2; j <= Amout; j++)
            {                
                t =profit[i-1][j];                //不选第i个公司产品
                for( k =1; k<= j; k++)        //选i公司的产品
                {
                    if(profit[i-1][j-k] + w[k][i] > t)    //w[k][i] :投入为k时公司i能获得的利润。
                        t = profit[i-1][j-k] + w[k][i];
                }
                profit[i][j] = t;                
            }
        }
        // Print the answer to standard output(screen).
        /*
        for( i =1; i<=company_num; i++)
            for(j =1; j<=Amout; j++)
            printf("profit[%d][%d] = %d\n",i ,j, profit[i][j]);
            */

        printf("%d\n", profit[company_num][Amout]);
    }

    return 0;//Your program should return 0 on normal termination.
}

 

技术分享

 

问题的描述如上,需要投资多个公司里的产品,每个公司最多投资一个产品,即可以认为公司是一组,该组中只能选一个。要求求得能够获得的最大收益。

 

代码如下:

 

分组背包问题描述与实现

标签:

原文地址:http://www.cnblogs.com/chenxf0619/p/4335686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!