theme: channing-cyan
开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第6天,点击查看活动详情
Charm Bracelet
Time Limit: 1000MS | Memory Limit: 65536K | |
---|---|---|
Total Submissions: 70676 | Accepted: 29271 |
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(1 ≤ N ≤ 3,402) 件物品和一个容量为V的背包。第i件物品的重量是w[i](1 ≤ Wi ≤ 400),价值是d[i](1 ≤ Di ≤ 100)。求解将哪些物品装入背包可使这些物品的重量总和不超过背包容量M(1 ≤ M ≤ 12,880),且价值总和最大。
解析
这就是01背包问题。01背包的约束条件是给定几种物品,每种物品有且只有一个,并且有权值和体积两个属性。在01背包问题中,因为每种物品只有一个,对于每个物品只需要考虑选与不选两种情况。如果不选择将其放入背包中,则不需要处理。如果选择将其放入背包中,由于不清楚之前放入的物品占据了多大的空间,需要枚举将这个物品放入背包后可能占据背包空间的所有情况。
01背包问题是经典的动态规划问题:
阶段:在前N件物品中,选取若干件物品放入背包中
状态:在前N件物品中,选取若干件物品放入所剩空间为W的背包中的所能获得的最大价值
决策:第N件物品放或者不放
由此可推出状态转移方程:
j >= w[i] dp[j] = max(dp[j], dp[j - w[i] + c[i])
标程
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
int dp[maxn],w[maxn],v[maxn];
int main(){
int n,s;
cin>>n>>s;
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)cin>>w[i]>>v[i];
for(int i=1;i<=n;i++)
for(int j=s;j>=w[i];j--)
dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
cout<<dp[s]<<endl;
}
暂无评论内容