1. 程式人生 > >Charm Bracelet

Charm Bracelet

earch ota urn sep inf stream rain clas ron

題目鏈接:http://poj.org/problem?id=3624

Charm Bracelet
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 47823 Accepted: 20322

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

Source

USACO 2007 December Silver 題目大意:輸入n,m,n代表n個物品,m代表背包最多能背多重,下面n行每行兩個數,分別代表每種物品的重量和價值,要求價值最大 思路:這題可以說是01背包的裸題了,但是這題不能用二維數組來做,會超內存,只能用一維 看代碼:
#include<iostream>
#include<string.h>
#include<map>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<ctype.h>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
typedef long long ll;
using namespace std;
const ll mod=1e9;
const int maxn=3402+5;
const int maxm=12880+5;
const int maxx=1e4+10;
const ll maxe=1000+10;
#define INF 0x3f3f3f3f3f3f
#define Lson l,mid,rt<<1
#define Rson mid+1,r,rt<<1|1
struct p
{
    int w,v;
}a[maxn];
int dp[maxm];//dp[i]代表重量為i時最大價值
int main()
{
    int n,m;
    cin>>n>>m;
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;i++)
    {
        cin>>a[i].w>>a[i].v;
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=m;j>=0;j--)//這裏只能是從大往小遍歷,因為如果從小往大了遍歷的話,會重復用到一個物品
        {
            if(j>=a[i].w) dp[j]=max(dp[j],dp[j-a[i].w]+a[i].v);
        }
    }
    cout<<dp[m]<<endl;
    return 0;
}

Charm Bracelet