01背包 实例

01背包实例

看了并理解了dd大牛写的背包九讲中的01背包,然后看了poj上面的3624这道题

Charm Bracelet

 

 

Description

Bessie has gone to the mall's jewelry store and spies a charm bracelet. Of course, she'd like to fill it with the best charms possible from the N (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weightWi (1 ≤ Wi ≤ 400), a 'desirability' factor Di (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M (1 ≤ M ≤ 12,880).

Given that weight limit as a constraint and a list of the charms with their weights and desirability rating, deduce the maximum possible sum of ratings.

Input

* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: Wi and Di

Output

* Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints

Sample Input

4 6
1 4
2 6
3 12
2 7

Sample Output

23

 

 

 

抽象一下题意就是:有N件大小和价值都可能不同的物品,放入容量为M的容器中,求解所能达到的最大价值。

首先是确定基本思路即状态转移方程

 f[v]=max{f[v],f[v-c[i]]+w[i]};(这个是优化了空间之后的转移方程)

背包问题的主要解题思路就是状态转移了,从而优化时间和空间

在输入某件物品后就要依次确定这件物品是否要放入容量为V到c的背包

当判断是否要把某件物品放入容量为j的背包中时只需把不把这件物品放入时的总价值与容量为j-c的背包所能达到的最大价值加上这件物品的价值比较,那么此时容量为j的背包所能达到的最大价值就是这两者的大者。

在具体写代码时还可以优化下时间

++++++++++++++++++++++++

 

#include

#define max(a,b) a>b?a:b

main()

{

    int f[3403]={0};

    int N,V,c,w,i,j;

    scanf("%d %d",&N,&V);

    for(i=0;i

    {

        scanf("%d %d",&c,&w);

        for(j=V;j>=c;j--)

        {

            f[j]=max(f[j],f[j-c]+w);

        }

    }

    printf("%d/n",f[V]);

}

++++++++++++++++++++++++

 

你可能感兴趣的:(ACM)