zoukankan      html  css  js  c++  java
  • ACboy needs your help(HDU 1712 分组背包入门)

    ACboy needs your help

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


    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
     
    Source
     
    分组背包,背包容量m,物品分为n组,每组只能取一件,求背包最大价值。
    dp[i][j]表示对于前i组物品,背包容量为j时的最大价值,此时对于每种dp[i][j]需要遍历第i组的每一个物品,求出最大的dp[i][j];
     
    状态转移方程:
              dp[i][j]=max(dp[i][j],dp[i-1][j-k]+ma[i][k])
     
     1 #include <iostream>
     2 #include <cstring>
     3 #include <cstdio>
     4 #include <algorithm>
     5 using namespace std;
     6 #define Max 105
     7 int dp[Max][Max],ma[Max][Max];
     8 int n,m;
     9 int main()
    10 {
    11     int i,j;
    12     memset(ma,0,sizeof(ma));
    13     freopen("in.txt","r",stdin);
    14     while(scanf("%d%d",&n,&m))
    15     {
    16         if(n==0&&m==0)
    17             break;    
    18         for(i=1;i<=n;i++)
    19             for(j=1;j<=m;j++)
    20                 scanf("%d",&ma[i][j]);
    21         memset(dp,0,sizeof(dp));
    22         for(i=1;i<=n;i++)
    23         {
    24             for(j=1;j<=m;j++)
    25             {
    26                 for(int k=0;k<=j;k++)
    27                 {
    28                     if(dp[i][j]<dp[i-1][j-k]+ma[i][k])
    29                         dp[i][j]=dp[i-1][j-k]+ma[i][k];
    30                 }
    31                 //cout<<dp[i][j]<<" ";
    32             }
    33         //    cout<<endl;
    34         }
    35         printf("%d
    ",dp[n][m]);
    36     }
    37     return 0;
    38 }
     
  • 相关阅读:
    文字有阴影效果
    asp.net(c#)将彩色图片变灰阶图片
    C#异步调用的方法
    PHP获取指定月份的第一天开始和最后一天结束的时间戳函数
    php 获取当前用户的IP
    网站前端性能优化
    grep命令的使用
    学C++的经验总结
    主键、唯一键与唯一索引的区别
    shell的比较运算符
  • 原文地址:https://www.cnblogs.com/a1225234/p/5318929.html
Copyright © 2011-2022 走看看