多重背包

 
Time Limit: 1sec    Memory Limit:256MB
Description
Ouyang has 6 kinds of coins.
The number of the i-th coin is N[i] (0<=i<6).
Their value and weight are as follewed:
0. $0.01, 3g
1. $0.05, 5g
2. $0.10, 2g
3. $0.25, 6g
4. $0.50, 11g
5. $1, 8g
Ouyang want to run away from home with his coins.
But he is so weak that he can only carray M gram of coins.
Given the number of each coin he has, what is the maximal value of coins he can take?
 
Input
There are multiple cases.
Each case has one line with 7 integers: M (1<=M<=10000), A[i], (0<=i<6, 0<=A[i]<=100000).
 
Output

 The maximal value of coins he can take.

Sample Input
Copy sample input to clipboard
1 1 1 1 1 1 1
38 3  1  10  4  2  1
75 8  5  23  4  2  4
Sample Output
$0.00
$2.40
$6.10


#include 
#include 
#include 
#include  

using namespace std;

double value[10]={0,0.01,0.05,0.10,0.25,0.50,1.00};
int weight[10]={0,3,5,2,6,11,8};
int num[10];
double res[10][100005];
int main()
{
    int gram;
    while(cin >> gram){
        int ncount=0;
        for(int i=1; i <= 6; ++i){
            cin >> num[i];
        }
        for(int i=0; i <= 6; i++) res[i][0]=0;
        for(int i=0; i <= gram; i++) res[0][i]=0; 
        
        for(int i=1; i <= 6; ++i){
            for(int w=0; w <= gram; ++w){
                res[i][w]=0;
                ncount=min(num[i],w/weight[i]);
                for(int j=0; j <= ncount; ++j){
                    res[i][w]=max(res[i][w],res[i-1][w-j*weight[i]]+j*1.0*value[i]);
                }
            }
        }
        cout << "$" << fixed << setprecision(2) << res[6][gram] << endl;
    }
}            

多重背包就是说每个物品的件数不一定,所以只要在原先的基础加多一层for循环,判断放入一件,两件。。。。等等时的情况就好,不过状态转移方程要变成

res[i][w]=max(res[i][w],res[i-1][w-j*weight[i]]+j*1.0*value[i]) 这里比较的不是res[i-1][w],而是res[i][w],也就是跟不放进当前这件比较


另外自己也看了下面一维解决背包,主要就是第二层的for要逆序



你可能感兴趣的:(算法)