zoukankan      html  css  js  c++  java
  • 分组背包 例题: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): 10880    Accepted 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
    ",dp[m]);
        }
        return 0;
    }
  • 相关阅读:
    RabbitMQ
    Java 多线程
    Java 多线程
    Java 多线程
    Java 多线程
    Springboot
    SpringBoot
    SpringCloud Config
    Financial
    Hystrix
  • 原文地址:https://www.cnblogs.com/kongbursi-2292702937/p/13993077.html
Copyright © 2011-2022 走看看