算法学习->背包问题(dp)小结

一、背包问题的三种类型

1、01背包

有编号分别为1~n的n件物品,它们的重量分别是啊w[1],w[2],….w[n],它们的价值分别是v[1],v[2],…..v[n],每件物品数量只有一个,现在给你个最大承重为W的背包,如何让背包里装入的物品具有最大的价值总和V?
模板:

//  01背包
void ZeroOnepark(int val, int vol)
{
    for (int j = v ; j >= vol; j--)
    {
        dp[j] = max(dp[j], dp[j - vol] + val);
    }
}

2、完全背包

有编号分别为1~n的n件物品,它们的重量分别是啊w[1],w[2],….w[n],它们的价值分别是v[1],v[2],…..v[n],每件物品数量有无数个,现在给你个最大承重为W的背包,如何让背包里装入的物品具有最大的价值总和V?
模板:

//  完全背包
void Completepark(int val, int vol)
{
    for (int j = vol; j <= v; j++)
    {
        dp[j] = max(dp[j], dp[j - vol] + val);
    }
}

3、多重背包

有编号分别为1~n的n件物品,它们的重量分别是啊w[1],w[2],….w[n],它们的价值分别是v[1],v[2],…..v[n],每件物品数量有cnt[1],cnt[2],….cnt[n]个,现在给你个最大承重为W的背包,如何让背包里装入的物品具有最大的价值总和V?
模板:

const int MAXN = 101;
const int SIZE = 50001;

int dp[SIZE];
int volume[MAXN], value[MAXN], c[MAXN];
int n, v;           //  总物品数,背包容量

//  01背包
void ZeroOnepark(int val, int vol)
{
    for (int j = v ; j >= vol; j--)
    {
        dp[j] = max(dp[j], dp[j - vol] + val);
    }
}

//  完全背包
void Completepark(int val, int vol)
{
    for (int j = vol; j <= v; j++)
    {
        dp[j] = max(dp[j], dp[j - vol] + val);
    }
}

//  多重背包
void Multiplepark(int val, int vol, int amount)
{
    if (vol * amount >= v)
    {
        Completepark(val, vol);
    }
    else
    {
        int k = 1;
        while (k < amount)
        {
            ZeroOnepark(k * val, k * vol);
            amount -= k;
            k <<= 1;
        }
        if (amount > 0)
        {
            ZeroOnepark(amount * val, amount * vol);
        }
    }
}

int main()
{
    while (cin >> n >> v)
    {
        for (int i = 1 ; i <= n ; i++)
        {
            cin >> volume[i] >> value[i] >> c[i];      //   费用,价值,数量
        }
        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= n; i++)
        {
            Multiplepark(value[i], volume[i], c[i]);
        }
        cout << dp[v] << endl;
    }
    return 0;
}

二、多重背包的二进制优化

由于一个数cnt【i】可以经过二进制分解(为什莫要二进制,因为二进制里只有0和1)为多个数的和,所以多重背包可以转化为01背包来解。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define LL long long
#define MAXN 1000100
using namespace std;

int N;//物品个数
int V;//背包容量
int Weight[MAXN];
int Value[MAXN];
int Num[MAXN];
int f[MAXN];

/*
f[v]:表示把前i件物品放入容量为v的背包中获得的最大收益。
f[v] = max(f[v],f[v - Weight[i]] + Value[i]);
v的为逆序
*/
void ZeroOnePack(int nWeight,int nValue)
{
    for (int v = V;v >= nWeight;v--)
    {
        f[v] = max(f[v],f[v - nWeight] + nValue);
    }
}

/*
f[v]:表示把前i件物品放入容量为v的背包中获得的最大收益。
f[v] = max(f[v],f[v - Weight[i]] + Value[i]);
v的为增序
*/
void CompletePack(int nWeight,int nValue)
{
    for (int v = nWeight;v <= V;v++)
    {
        f[v] = max(f[v],f[v - nWeight] + nValue);
    }
}

int MultiKnapsack()
{
    int k = 1;
    int nCount = 0;
    for (int i = 1;i <= N;i++)
    {
        if (Weight[i] * Num[i] >= V)
        {
            //完全背包:该类物品原则上是无限供应,
            //此时满足条件Weight[i] * Num[i] >= V时,
            //表示无限量供应,直到背包放不下为止.
            CompletePack(Weight[i],Value[i]);
        }
        else
        {
            k = 1;
            nCount = Num[i];
            while(k <= nCount)//二进制优化
            {
                ZeroOnePack(k * Weight[i],k * Value[i]);
                nCount -= k;
                k <<= 2;
            }
            ZeroOnePack(nCount * Weight[i],nCount * Value[i]);
        }
    }
    return f[V];
}
int main()
{
    while(cin>>V)
    {
        cin>>N;
        for(int i=1;i<=N;i++)
        {
            scanf("%d%d",&Num[i],&Value[i]);
            Weight[i]=Value[i];//费用与价值相等
        }
            memset(f,0,sizeof(f));
            int ans=MultiKnapsack();
            cout<<ans<<endl;
    }
    return 0;
}

三、练习题

1、F - FATE

最近xhd正在玩一款叫做FATE的游戏,为了得到极品装备,xhd在不停的杀怪做任务。久而久之xhd开始对杀怪产生的厌恶感,但又不得不通过杀怪来升完这最后一级。现在的问题是,xhd升掉最后一级还需n的经验值,xhd还留有m的忍耐度,每杀一个怪xhd会得到相应的经验,并减掉相应的忍耐度。当忍耐度降到0或者0以下时,xhd就不会玩这游戏。xhd还说了他最多只杀s只怪。请问他能升掉这最后一级吗?

Input

输入数据有多组,对于每组数据第一行输入n,m,k,s(0 < n,m,k,s < 100)四个正整数。分别表示还需的经验值,保留的忍耐度,怪的种数和最多的杀怪数。接下来输入k行数据。每行数据输入两个正整数a,b(0 < a,b < 20);分别表示杀掉一只这种怪xhd会得到的经验值和会减掉的忍耐度。(每种怪都有无数个)

Output

输出升完这级还能保留的最大忍耐度,如果无法升完这级输出-1。

Sample Input

10 10 1 10
1 1
10 10 1 9
1 1
9 10 2 10
1 1
2 2

Sample Output

0
-1
1

AC代码:

#include<iostream>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<algorithm>
using namespace std;

#define maxn 110
int dp[maxn][maxn],a[maxn],b[maxn];

int main(){
    int n,m,k,s,flag=0;
    while(scanf("%d%d%d%d",&n,&m,&k,&s)!=EOF){
        flag=0;
        memset(dp,0,sizeof(dp));
        for(int i=0;i<k;i++){
            scanf("%d%d",&a[i],&b[i]);
        }
        int sum=0;
        for(int i=1;i<=m;i++){
            for(int j=0;j<=k-1;j++){
                for(int u=1;u<=s;u++){
                    if(b[j]<=i){
                        dp[i][u]=max(dp[i-b[j]][u-1]+a[j],dp[i][u]);//忍耐度为i,杀了u个怪
                    }
                }
            }
            if(dp[i][s]>=n){
                printf("%d\n",m-i);
                flag=1;
                break;
            }
        }
        if(flag==0){
            printf("-1\n");
        }
    }
    return 0;
}

2、A - Cash Machine

A Bank plans to install a machine for cash withdrawal. The machine is able to deliver appropriate @ bills for a requested cash amount. The machine uses exactly N distinct bill denominations, say Dk, k=1,N, and for each denomination Dk the machine has a supply of nk bills. For example,

扫描二维码关注公众号,回复: 2700018 查看本文章

N=3, n1=10, D1=100, n2=4, D2=50, n3=5, D3=10

means the machine has a supply of 10 bills of @100 each, 4 bills of @50 each, and 5 bills of @10 each.

Call cash the requested amount of cash the machine should deliver and write a program that computes the maximum amount of cash less than or equal to cash that can be effectively delivered according to the available bill supply of the machine.

Notes:
@ is the symbol of the currency delivered by the machine. For instance, @ may stand for dollar, euro, pound etc.

Input

The program input is from standard input. Each data set in the input stands for a particular transaction and has the format:

cash N n1 D1 n2 D2 … nN DN

where 0 <= cash <= 100000 is the amount of cash requested, 0 <=N <= 10 is the number of bill denominations and 0 <= nk <= 1000 is the number of available bills for the Dk denomination, 1 <= Dk <= 1000, k=1,N. White spaces can occur freely between the numbers in the input. The input data are correct.

Output

For each set of data the program prints the result to the standard output on a separate line as shown in the examples below.

Sample Input

735 3 4 125 6 5 3 350
633 4 500 30 6 100 1 5 0 1
735 0
0 3 10 100 10 50 10 10

Sample Output

735
630
0
0

Hint

The first data set designates a transaction where the amount of cash requested is @735. The machine contains 3 bill denominations: 4 bills of @125, 6 bills of @5, and 3 bills of @350. The machine can deliver the exact amount of requested cash.

In the second case the bill supply of the machine does not fit the exact amount of cash requested. The maximum cash that can be delivered is @630. Notice that there can be several possibilities to combine the bills in the machine for matching the delivered cash.

In the third case the machine is empty and no cash is delivered. In the fourth case the amount of cash requested is @0 and, therefore, the machine delivers no cash.

AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define LL long long
#define MAXN 1000100
using namespace std;

int N;//物品个数
int V;//背包容量
int Weight[MAXN];
int Value[MAXN];
int Num[MAXN];
int f[MAXN];

/*
f[v]:表示把前i件物品放入容量为v的背包中获得的最大收益。
f[v] = max(f[v],f[v - Weight[i]] + Value[i]);
v的为逆序
*/
void ZeroOnePack(int nWeight,int nValue)
{
    for (int v = V;v >= nWeight;v--)
    {
        f[v] = max(f[v],f[v - nWeight] + nValue);
    }
}

/*
f[v]:表示把前i件物品放入容量为v的背包中获得的最大收益。
f[v] = max(f[v],f[v - Weight[i]] + Value[i]);
v的为增序
*/
void CompletePack(int nWeight,int nValue)
{
    for (int v = nWeight;v <= V;v++)
    {
        f[v] = max(f[v],f[v - nWeight] + nValue);
    }
}

int MultiKnapsack()
{
    int k = 1;
    int nCount = 0;
    for (int i = 1;i <= N;i++)
    {
        if (Weight[i] * Num[i] >= V)
        {
            //完全背包:该类物品原则上是无限供应,
            //此时满足条件Weight[i] * Num[i] >= V时,
            //表示无限量供应,直到背包放不下为止.
            CompletePack(Weight[i],Value[i]);
        }
        else
        {
            k = 1;
            nCount = Num[i];
            while(k <= nCount)
            {
                ZeroOnePack(k * Weight[i],k * Value[i]);
                nCount -= k;
                k <<= 2;
            }
            ZeroOnePack(nCount * Weight[i],nCount * Value[i]);
        }
    }
    return f[V];
}
int main()
{
    while(cin>>V)
    {
        cin>>N;
        for(int i=1;i<=N;i++)
        {
            scanf("%d%d",&Num[i],&Value[i]);
            Weight[i]=Value[i];//费用与价值相等
        }
            memset(f,0,sizeof(f));
            int ans=MultiKnapsack();
            cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wuyileiju__/article/details/81348999