POJ 1384 Piggy-Bank(DP完全背包)

#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;

//很简单的完全背包问题,MLE了
//复习了一下空间的优化 ^_^ ~ ~

LL dp[10005];
int w[505], p[505];

int main(){
	int t; scanf("%d", &t);
	while (t--){
		memset(dp, 0, sizeof dp);
		int E, F; scanf("%d %d", &E, &F);
		int tol = F - E;
		int n; scanf("%d", &n);
		for (int i = 1; i <= n; i++)scanf("%d %d", p + i, w + i);

		/*for (int j = 1; j <= n; j++)dp[0][j] = 0;
		for (int i = 1; i <= tol; i++)dp[i][1] = (i >= w[1] && i%w[1] == 0) ? (i / w[1] * p[1]) : (LL(50000)*10000+1);

		for (int j = 2; j <= n; j++){
			for (int i = 1; i < w[j]; i++)dp[i][j] = dp[i][j - 1];
			for (int i = w[j]; i <= tol; i++){
				dp[i][j] = min(dp[i - w[j]][j] + p[j], dp[i][j - 1]);
			}
		}*/

		//dp[i]表示 i 的重量最少能有多少钱
		//初始化时是没有钱币时,所以都是impossible
		for (int i = 1; i <= tol; i++)dp[i] = (LL)50000 * 10000 + 1;

		for (int j = 1; j <= n; j++){
			//这句话可以省略,因为本层的dp[i]跟上一层的dp[i]没有变化
			//for (int i = 1; i < w[j]; i++)dp[i] = dp[i];
			for (int i = w[j]; i <= tol; i++) {
				dp[i] = min(dp[i - w[j]] + p[j], dp[i]);
			}
		}

		if (dp[tol] == (LL)50000 * 10000 + 1){
			printf("This is impossible.\n");
		}
		else{
			printf("The minimum amount of money in the piggy-bank is %I64d.\n", dp[tol]);
		}


	}
	return 0;
}

你可能感兴趣的:(POJ 1384 Piggy-Bank(DP完全背包))