分析:题目的意思是,给出需要的总金额和每种面值钱的数量,求能够获得的接近总金额的最大的金额。总金额0 <=cash <= 100000,所以背包的容量就是100000。而cost和weight都是面值D[k]。
又是一道多重背包的问题,毫无压力。写个代码练练手吧~
#include <iostream>
using namespace std;
int F[100001];
int n[11];
int D[11];
int max(int a, int b)
{
return a>b?a:b;
}
void ZeroOnePack(int cost, int weight, int V)
{
for (int v=V; v>=cost; --v)
F[v] = max(F[v], F[v-cost]+weight);
}
void CompletePack(int cost, int weight, int V)
{
for (int v=cost; v<=V; ++v)
F[v] = max(F[v], F[v-cost]+weight);
}
void MultiPack(int cost, int weight, int V, int amount)
{
if (cost*amount>=V) {
CompletePack(cost, weight, V);
return;
}
int k =1;
while (k<amount) {
ZeroOnePack(cost*k, cost*k, V);
amount -= k;
k *= 2;
}
ZeroOnePack(cost*amount, weight*amount, V);
}
int main(int argc, char **argv)
{
int cash;
int N;
while (cin>>cash>>N) {
for (int i=1; i<=N; ++i) {
cin>>n[i]>>D[i];
}
memset(F, 0, sizeof(int)*100001);
for (int i=1; i<=N; ++i)
MultiPack(D[i], D[i], cash, n[i]);
cout<<F[cash]<<endl;
}
system("pause");
return 0;
}
47MS过,done!