题目来源:http://noi.openjudge.cn/ch0206/7113/
7113: Charm Bracelet
总时间限制: 1000ms 内存限制: 65536kB
描述
Bessie has gone to the mall'sjewelry store and spies a charm bracelet. Of course, she'd like to fill it withthe best charms possible from the N(1≤ N≤ 3,402) availablecharms. Each charm iinthe 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 whoseweight is no more than M(1≤ M≤ 12,880).
Given that weight limit as aconstraint and a list of the charms with their weights and desirability rating,deduce the maximum possible sum of ratings.
输入
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
输出
Line 1: A single integer that is the greatest sum of charmdesirabilities that can be achieved given the weight constraints
样例输入
4 6
1 4
2 6
3 12
2 7
样例输出
23
来源
USACO 2007 December Silver
-----------------------------------------------------
解题思路
0-1背包,dp[i][j] (i=0,1,…,n;j=0,1,…,m)表示只考虑前i个物品且背包重量为j时的最大价值。递推式:
dp[i][j] =max(dp[i-1][j], dp[i-1][j-w[i]]+d[i])
一维数组优化的时候要注意倒着从m开始遍历到w[i]避免覆盖问题。
-----------------------------------------------------
代码
// 0-1背包 // 一维动态规划优化版本 #include<iostream> #include<fstream> using namespace std; int dp[12890] = {}; int main() { #ifndef ONLINE_JUDGE ifstream fin("0206_7113.txt"); int n,m,w,d,i,j; fin >> n >> m; for (i=1; i<=n; i++) { fin >> w >> d; for (j=m; j>=w; j--) // 一维优化的时候要倒着遍历,这样不会造成覆盖问题 { dp[j] = max(dp[j], dp[j-w]+d); } } fin.close(); cout << dp[m]; return 0; #endif #ifdef ONLINE_JUDGE int n,m,w,d,i,j; cin >> n >> m; for (i=1; i<=n; i++) { cin >> w >> d; for (j=m; j>=w; j--) { dp[j] = max(dp[j], dp[j-w]+d); } } cout << dp[m]; #endif }