1. 程式人生 > 實用技巧 >分組揹包 例題:hdu 1712 ACboy needs your help

分組揹包 例題:hdu 1712 ACboy needs your help

分組揹包需求

有N件物品,告訴你這N件物品的重量以及價值,將這些物品劃分為K組,每組中的物品互相沖突,最多選一件,求解將哪些物品裝入揹包可使這些物品的費用綜合不超過揹包的容量,且價值總和最大。

解題模板

和01揹包很相似,就是在每一個組內列舉每一個物品,注意要先列舉揹包容量之後列舉屬於某個組的所有物品,這樣的話才可以保證“每組中的物品互相沖突,最多選一件

for 所有的組k
    for v=V..0
        for 所有的i屬於組k
            dp[v]=max{dp[v],dp[v-weight[i]]+value[i]}

例題:

ACboy needs your help

Time Limit: 1000/1000 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10880Accepted Submission(s): 5993


Problem Description ACboy has N courses this term, and he plans to spend at most M days on study.Of course,the profit he will gain from different course depending on the days he spend on it.How to arrange the M days for the N courses to maximize the profit?


Input The input consists of multiple data sets. A data set starts with a line containing two positive integers N and M, N is the number of courses, M is the days ACboy has.
Next follow a matrix A[i][j], (1<=i<=N<=100,1<=j<=M<=100).A[i][j] indicates if ACboy spend j days on ith course he will get profit of value A[i][j].
N = 0 and M = 0 ends the input.


Output For each data set, your program should output a line which contains the number of the max profit ACboy will gain.


Sample Input 2 2 1 2 1 3 2 2 2 1 2 1 2 3 3 2 1 3 2 1 0 0

Sample Output 3 4 6

/*
題意:
給你n個課程,m天時間
每一個課程只能選擇一次,而且學習每一個課程不同天數有不同程度的收益
問你m天內你的最大收益

題解:
分組揹包
*/
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=105;
int dp[maxn],w[maxn][maxn];
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m) && n+m)
    {
        for(int i=1;i<=n;++i)
        {
            for(int j=1;j<=m;++j)
            {
                scanf("%d",&w[i][j]);
            }
        }
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;++i)
        {
            for(int j=m;j>=1;--j)
            {
                for(int k=1;k<=j;++k)
                {
                    dp[j]=max(dp[j],dp[j-k]+w[i][k]);
                }
            }
        }
        printf("%d\n",dp[m]);
    }
    return 0;
}