HDU 1712 ACboy needs your help (簡單分組揹包)

ACboy needs your help

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


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天。不同課程的收益取決於在它上花費的時間。怎樣爲N門課程安排M天讓總收益最大化? 解題思路:就是一道分組揹包模板題。 以下是揹包九講的內容: 6 分組的揹包問題 6.1 問題 有N件物品和一個容量爲V 的揹包。第i件物品的費用是Ci,價值是Wi。這 些物品被劃分爲K組,每組中的物品互相沖突,最多選一件。求解將哪些物品 裝入揹包可使這些物 品的費用總和不超過揹包容量,且價值總和最大。 6.2 算法 這個問題變成了每組物品有若干種策略:是選擇本組的某一件,還是一件 都不選。也就是說設F[k,v]表示前k組物品花費費用v能取得的最大權值,則 有:  F[k,v] = max{F[k−1,v],F[k−1,v−Ci] + Wi |item i ∈ group k} 使用一維數組的僞代碼如下: for k = 1 to K for v = V to 0 for item i in group k F[v] = max{F[v],F[v−Ci] + Wi} 這裏三層循環的順序保證了每一組內的物品最多隻有一個會被添 加到揹包中。 另外,顯然可以對每組內的物品應用2.3中的優化。 6.3 小結 分組的揹包問題將彼此互斥的若干物品稱爲一個組,這建立了一個很好的 模型。不少揹包問題的變形都可以轉化爲分組的揹包問題(例如7),由分組的 揹包問題進一步可 定義“泛化物品”的概念,十分有利於解題。
<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=105;
int value[maxn][maxn];
int dp[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",&value[i][j]);
            }
        }
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            for(int j=m;j>=0;j--)
            {
                 for(int k=1;k<=j;k++)
                 {
                     if(dp[j]<dp[j-k]+value[i][k])
                        dp[j]=dp[j-k]+value[i][k];
                 }
            }
        }
        printf("%d\n",dp[m]);
    }
    return 0;
}</span>


發佈了106 篇原創文章 · 獲贊 5 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章