问题如图:
常规动态规划解法
使用二维数组:
#include<stdio.h>
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
int B(0);
int pi, vi;
vector<int> P;
vector<int> V;
P.resize(3000);
V.resize(3000);
int n(0);
scanf("%d", &B);
while (1)
{
scanf("%d", &P[n]);
scanf("%d", &V[n]);
++n;
char c = getchar();
if (c == '\n')
{
break;
}
}
vector<vector<int>> F;
F.resize(n);
for (auto i = 0; i < n;++i)
{
F[i].resize(B+1);
}
//初始化F[0][j]
for (auto j = 0; j < P[0];++j)
F[0][j] = 0;
for (auto j = P[0]; j <=B; ++j)
F[0][j] = V[0];
for (auto i = 1; i < n; ++i)
{
for (auto j = 0; j < P[i];++j)
{
F[i][j] = F[i - 1][j];
}
for (auto j = P[i]; j <= B;++j)
{
F[i][j] = max(F[i-1][j],F[i-1][j-P[i]]+V[i]);
}
}
printf("%d\n", F[n-1][B]);
return 0;
}
常规方法需要M*N 内存,为了节省内存,可使用一维数组,内存需求可降低到M
参见:http://blog.csdn.net/qq_32036091/article/details/51301912
#include<stdio.h>
#include<vector>
#include <algorithm>
using namespace std;
int main()
{
int B(0);
int pi, vi;
vector<int> P;
vector<int> V;
P.resize(3000);
V.resize(3000);
int n(0);
scanf("%d", &B);
while (1)
{
scanf("%d", &P[n]);
scanf("%d", &V[n]);
++n;
char c = getchar();
if (c == '\n')
{
break;
}
}
vector<int> F;
F.resize(B+1);
for (auto i = 0; i < n;++i)
{
for (auto j = B; j >= P[i];--j)
{
F[j] = max(F[j],F[j-P[i]]+V[i]);
}
}
printf("%d\n", F[B]);
return 0;
}