poj 1384 完全揹包的最小值

題意:

有一個存錢罐,不砸碎它,稱重得到裏面硬幣的重量,

硬幣分爲面值和重量,給定重量和麪值,求達到該重量的最小面值

解法:

注意幾個問題:1.完全揹包的循環方向

                            2.注意要滿足恰好等於給定的重量,不能比它輕或者重,所以對於初始化有要求

                            3.注意是求最小值,不是常見的最大值

初始化:f數組,0設置爲0,其餘設置爲正無窮

               循環方向從0-V閉區間

               如果迭代更新了f[v]那麼就找到了,否則沒找到

#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <queue>
using namespace std;

///宏定義
const int  INF = 990000000;
const int maxn = 15000 ;
const int MAXN = maxn;
///全局變量 和 函數
int max(int a, int b)
{
	return a > b ? a : b;
}

int T;
int E, F;
int N;
int P[maxn];
int W[maxn];
int ffmax[maxn];
int ffmin[maxn];
int main()
{
	///變量定義
	int i, j, m;
	scanf("%d", &T);
	int cases = 1;
	while(T--)
	{
		scanf("%d %d", &E, &F);
		scanf("%d", &N);
		for (i = 0; i < N; i++)
		{
			scanf("%d %d", &P[i], &W[i]);
		}
		
		int V = F - E;
		for (i = 0; i <= V; i++)//初始化很關鍵!
		{
			ffmax[i] = INF;
		}
		ffmax[0] = 0;
		//0-1揹包經典求解
		for (i = 0; i < N; i++)
		{
			for (j = 0; j <= V; j++)
			{
				if (j >= W[i])
				{
					if (ffmax[j] > ffmax[j - W[i]] + P[i])  //更改大於小於號!
					{
						ffmax[j] = ffmax[j - W[i]] + P[i];
					}
				}
			}
		}
		
		int ans = ffmax[V];
		if (ans != INF)
		{
			printf("The minimum amount of money in the piggy-bank is %d.\n", ans);
		}
		else
		{
			printf("This is impossible.\n");
		}
	}
	
	///結束
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章