POJ 3260 The Fewest Coins

题目描述

 

总结

1. 完全背包框架都想了半天

2. 我随机取了个背包的上限, 超时了

 

 

代码 超时

/*
 * source.cpp
 *
 *  Created on: Apr 6, 2014
 *      Author: sangs
 */

#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <memory.h>
using namespace std;

const int INF = 0X3F3F3F3F;
const int MAXMONEY = 50000;
int val[2000];
int num[2000];

int dp[MAXMONEY+100];

void firstPass(int n, int target) {
	memset(dp, 0x3F, sizeof(dp));

	dp[0] = 0;
	for(int i = 0; i < n; i ++) {
		for(int j = MAXMONEY; j >= val[i]; j --) {
			for(int k = 0; k <= num[i]; k ++) {
				int totalMoney = k*val[i];
				if(j < totalMoney) continue;
				if(dp[j-totalMoney] == INF) continue;

				dp[j] = min(dp[j], dp[j-totalMoney] + k);
			}
		}
	}
}

int secondPass(int n, int target) {
	for(int i = 0; i < n; i ++) {
		for(int j = MAXMONEY-val[i]; j >= 0; j --) {
			if(dp[j+val[i]] == INF) continue;
			dp[j] = min(dp[j], dp[j+val[i]] + 1);
		}
	}
	return dp[target];
}

int main() {
	freopen("input.txt", "r", stdin);

	int n, target;
	while(scanf("%d%d", &n, &target) != EOF) {
		for(int i = 0; i < n; i ++) {
			scanf("%d", val+i);
		}
		for(int i = 0; i < n; i ++) {
			scanf("%d", num+i);
		}

		firstPass(n, target);
		int res = secondPass(n, target);
		if(res == INF)
			res = -1;
		printf("%d\n", res);
	}
	return 0;
}

  

posted @ 2014-04-06 16:14  周卓  阅读(136)  评论(0编辑  收藏  举报