现在的位置: 首页 > 综合 > 正文

[POJ_3624] 0-1背包 题解

2018年04月25日 ⁄ 综合 ⁄ 共 1492字 ⁄ 字号 评论关闭

本人半路出家   算法从未规范的学习过,前几天在学习DP的时候,同伴惊呼:你竟然不知道背包,此乃dp基础...... 

闲来无事,学学背包也好~

废话少说,题目如下:

Charm Bracelet
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 19607   Accepted: 8911

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

        题意:现在有N颗宝石,每颗宝石都有自己的重量W以及自己的价值D,现在我们来串手链,已知手链所能承受的最大重量为M,求得在手链能承受的最大重量之下,手链的最大价值。此题是典型的0-1背包。

       给出状态转移方程:  dp[j]=max(dp[j],   dp[j - w[i]]+D[i]);

因为手链的最大价值是不确定的,因此,dp的赋值为0

现给出AC代码

#include <iostream>
#include<string.h>
#include<cstdio>
using namespace std;
const int MAX = 3500;
const int Max = 13000;
int dp[13000];
int M[3500];
int D[13000];
int N,M1;

int main()
{
    int ans = -1;//赋值为负数
    memset(dp,0,sizeof(dp));
    scanf("%d%d",&N,&M1);
    for(int i = 1; i <= N; i++)
    {
        scanf("%d%d",&M[i],&D[i]);
    }
    for(int i = 1; i <= N; i++)
    {
        for(int j = M1; j >= M[i]; j--)
        {
            dp[j]=max(dp[j],dp[j-M[i]]+D[i]);
            ans = max(ans,dp[j]);
        }
    }
   printf("%d\n",ans);
    return 0;
}

抱歉!评论已关闭.