完全背包在背包九讲中有很详细的讲解,但是今天碰到题尝试了一下他给的算法,发现并不快,看了一下其他的代码,速度很快!
题目链接http://hihocoder.com/problemset/problem/1043
414ms
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int N, M;
int need[505], value[505];
int dp[100010] ;
int space[15];
int money[15];
void solve(int i,int &count)
{
int di = 1;
int max = M / need[i];
while(max-di>=0)
{
max -= di;
space[count] = di*need[i];
money[count] = di*value[i];
di = di << 1;
count++;
}
if (max > 0)
{
space[count] = max*need[i];
money[count] = max*value[i];
count++;
}
}
int main()
{
scanf("%d%d", &N, &M);
for (int i = 0; i < N; i++)
{
scanf("%d%d", &need[i], &value[i]);
int count = 1;
solve(i,count);
for (int j = 1; j < count; j++)
{
for (int k = M; k>=space[j];k--)
{
dp[k] = dp[k]>(dp[k - space[j]] + money[j]) ? dp[k] : (dp[k - space[j]] + money[j]);
}
}
}
cout << dp[M] << endl;
return 0;
}
175ms
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int N, M;
int need[505], value[505];
int dp[100010] ;
int main()
{
scanf("%d%d", &N, &M);
for (int i = 0; i < N; i++)
{
scanf("%d%d", &need[i], &value[i]);
for (int j = need[i]; j <= M;j++)
dp[j] = dp[j]>(dp[j - need[i]] + value[i]) ? dp[j] : (dp[j - need[i]] + value[i]);
}
cout << dp[M] << endl;
return 0;
}