Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 17400 | Accepted: 7901 |
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
这道题本身并没有什么难度,只是基础题~ 拿来复习用的~
#include<iostream>
using namespace std;
int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
int num,totalweight,weight[12880],value[12880];
int f[12880];
cin>>num>>totalweight;
for(int i=0;i<num;i++)
{
cin>>weight[i]>>value[i];
}
for(int i=0;i<num;i++)
{
for(int v=totalweight;v>=weight[i];v--)
{
f[v]=max(f[v],f[v-weight[i]]+value[i]);
}
}
cout<<f[totalweight]<<endl;
return 0;
}
后来用二维数组写一下~ 超时~
code:
#include<iostream>
#include<string.h>
using namespace std;
int v[12881]={0};
int w[12881]={0};
int dp[12881][12881];
int main()
{
int n,V;
while (cin>>n>>V)
{
for (int i=1;i<=n;i++)
{
cin>>v[i]>>w[i];
}
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
for(int j=0;j<=V;j++)
{
if(v[i]<=j )
dp[i][j]=max(dp[i-1][j-v[i]]+w[i],dp[i-1][j]);
else
dp[i][j]=dp[i-1][j]; //这一步一定要加上~
}
cout<<"---------------->(x轴) 体积"<<endl;;
for (int i=1;i<=n;i++)
{
cout<<"|";
for (int j=0;j<=V;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
cout<<"|"<<endl;
cout<<"Y轴 n"<<endl;
cout<<dp[n][V]<<endl;
}
return 0;
}
二维数组要注意的是那个
else
dp[i][j]=dp[i-1][j];
由于在上一步中如果超了体积 应直接赋值给dp[i][j]
不加else
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
4 6
1 4
2 6
3 12
2 7
---------------->(x轴) 体积
|0 4 4 4 4 4 4
|0 0 6 10 10 10 10
|0 0 0 12 12 18 22
|0 0 7 12 12 19 22
|
Y轴 n
22
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
正确的:
4 6 1 4 2 6 3 12 2 7 ---------------->(x轴) 体积 |0 4 4 4 4 4 4 |0 4 6 10 10 10 10 |0 4 6 12 16 18 22 |0 4 7 12 16 19 23 | Y轴 n 23
也就是说在给出的v值如果有相同值的时候 不加else 得出的答案会有错误~