POJ 1276 cash machine

分析:題目的意思是,給出需要的總金額和每種面值錢的數量,求能夠獲得的接近總金額的最大的金額。總金額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!


發佈了29 篇原創文章 · 獲贊 46 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章