首页 > 代码库 > poj 3624 Charm Bracelet

poj 3624 Charm Bracelet

Charm Bracelet
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 38561   Accepted: 16727

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

题目大意:意思就是给定你手上能承受多少珠子,然后要尽可能的选择价值大重量轻的珠子戴在手上,最后输出最大的价值。
题目思路:典型的0-1背包问题,一直WA的原因就是把它弄成了完全背包问题。若用完全背包的贪心策略,只能选出局部看来最优的方案,但是用动态规划可以解决这个问题。
#include<iostream>
#include<string.h>

using namespace std;

int max(int a,int b){
return a>b?a:b;
}
int main(){
    int wi,di;
    int dp[15000];

    int N,M;

    memset(dp,0,sizeof(dp));
    cin>>N>>M;
    for(int i=1;i<=N;i++){
        cin>>wi>>di;//从输入开始判断能否放入这个珠子

        for(int j=M;j>0;j--){//同样通过数组记录最大值
            if(j>=wi)
                dp[j]=max(dp[j],dp[j-wi]+di);//放完后的价值和未放之前的价值与放入的价值之和相比较,大的那方更新数组
        }
    }
    cout<<dp[M]<<endl;
}

 

poj 3624 Charm Bracelet