当前位置: 代码迷 >> 综合 >> HDU 1712—— ACboy needs your help【分组背包】
  详细解决方案

HDU 1712—— ACboy needs your help【分组背包】

热度:63   发布时间:2023-12-16 23:08:43.0

题目传送门

选课复习问题,没门课只能选一次,找个时间复习,求最大的收益。每门课对应一组,每个时间对应一个物品。


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天学习。a[i][j]表示如果在第i门课程上花费j天,他将获得值a[i][j]的利润。如何安排M天学习N门课程,以使利润最大化?


分析:

  • 分组背包
  • 模版题

AC代码:

#include <iostream>
#include <vector>
#include <utility>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <cstdio>
#include <fstream>
#include <set>
using namespace std;
typedef long long ll;const int INF = 0x3f3f3f;
const int MAXN = 1e4+ 100;int dp[MAXN];
int a[MAXN][MAXN];
int main(){
    int n,m;while(cin >> n >> m){
    memset(dp, 0, sizeof(dp));if(m==0 && n == 0)break;for(int i = 1; i<= n; i++){
    for(int j = 1; j <= m; j++){
    cin >> a[i][j];}}for(int i = 1; i <= n; i++){
    for(int j = m; j >= 0; j--){
    for(int k = 0; k <= m; k++){
    if(j >= k)dp[j] = max(dp[j], dp[j-k] +a[i][k]);}}}cout << dp[m]<<endl;}return 0;
}