zoukankan      html  css  js  c++  java
  • POJ 3624 Charm Bracelet (01)(背包入门)

    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 weight Wi (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

    01背包主要关系:
    if (dp[j]<dp[j-w[i]]+d[i])
                dp[j]=dp[j-w[i]]+d[i];

    对于题给的例子:

    1 2 3 2


    dp[1] 4 4 4 4


    dp[2] 4 6 6 7


    dp[3] 4 10 12 12


    dp[4] 4 10 16 13



    dp[5] 4 10 18 19



    dp[6] 4 10 22 23


    dp[j]表示容量为j时能放的最多东西。从1到n个物品一个一个的放和比较。
     1 #include<cstdio>
     2 #include<cstring>
     3 using namespace std;
     4 int main()
     5 {
     6     int w[3500],d[3500],n,m,i,j,dp[13500];
     7     while (~scanf("%d%d",&n,&m))
     8     {
     9         memset(dp,0,sizeof(dp));
    10         for (i=1;i<=n;i++) scanf("%d%d",&w[i],&d[i]);
    11         for (i=1;i<=n;i++)
    12         {
    13             for (j=m;j>=w[i];j--)
    14             if (dp[j]<dp[j-w[i]]+d[i])
    15             dp[j]=dp[j-w[i]]+d[i];
    16         }
    17         printf("%d
    ",dp[m]);
    18     }
    19 }
  • 相关阅读:
    Java学习笔记(一)语法
    【转,整理】C# 非托管代码
    HTML5学习笔记(七)WebSocket
    HTML5学习笔记(七)HTML5 服务器发送事件(Server-Sent Events)
    MySQL修改表格内容3
    MySQL修改表格内容2
    MySQL修改表格内容
    MySQL创建表格
    if-else if-else;多选择结构
    面向对象和面向过程的初步概念
  • 原文地址:https://www.cnblogs.com/pblr/p/4757096.html
Copyright © 2011-2022 走看看