下面是一个试图解决thisSPOJ问题的方法输入是:
一定数量硬币的总重量
所用货币的币值和相应的重量,其目的是找到给定货币量的最小可能货币价值。
我稍微修改了背包问题的动态规划解决方案,从背包问题的wikipedia article开始-我只是先按重量对硬币进行排序,这样我就不必遍历所有的硬币来获得最小的值,并且(希望)确保组合的重量等于容量。(请看代码,它非常简单,并且有注释。)
然而,根据法官的说法,我的算法给出了一个错误的答案你能告诉我这个算法有什么问题吗?
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
typedef unsigned int weight_t;
typedef unsigned int value_t;
struct coin {
weight_t weight;
value_t value;
};
coin make_coin(weight_t weight, value_t value) {
coin ret;
ret.weight = weight;
ret.value = value;
return ret;
}
bool compare_by_weight(const coin& coin1, const coin& coin2) {
return coin1.weight < coin2.weight;
}
int main() {
unsigned int test_cases;
cin >> test_cases;
while(test_cases--) {
//Initialization
unsigned int number_of_coins, n = 0;
weight_t empty_pig, full_pig, coin_weight, coins_weight;
value_t coin_value, min_value, current_value = 0;
vector<coin> coins;
vector<unsigned int> min_value_for_the_weight;
//Input
cin >> empty_pig >> full_pig;
cin >> number_of_coins;
n = number_of_coins;
while(n--) {
cin >> coin_value >> coin_weight;
coins.push_back(make_coin(coin_weight, coin_value));
}
//Input processing
coins_weight = full_pig - empty_pig;
sort(coins.begin(), coins.end(), compare_by_weight);
min_value_for_the_weight.resize(coins_weight+1);
for(unsigned int i = 0; i < coins_weight; i++) min_value_for_the_weight[i] = 0;
//For all weights
for(unsigned int i = 1; i <= coins_weight; i++) {
//Find the smallest value
min_value = numeric_limits<value_t>::max();
for(unsigned int j = 0; j < number_of_coins; j++) {
//The examined coin weights more or same than examined total weight and we either already have put a coin
//in, or this is the first one
if(coins[j].weight <= i && (min_value_for_the_weight[i - coins[j].weight] > 0 || i == coins[j].weight)){
current_value = coins[j].value + min_value_for_the_weight[i - coins[j].weight];
if(current_value < min_value) min_value = current_value;
} else break; // <- this I deleted to get accepted
}
if(min_value == numeric_limits<value_t>::max()) min_value = 0;
min_value_for_the_weight[i] = min_value;
}
//If the piggy empty, output zero
if(!min_value_for_the_weight[coins_weight] && coins_weight != 0)
cout << "This is impossible." << endl;
else
cout << "The minimum amount of money in the piggy-bank is " << min_value_for_the_weight[coins_weight] << "." << endl;
}
return 0;
}
最佳答案
caseempty_pig == full_pig
是有问题的,因为您忽略了重复逻辑特殊的casemin_value_for_the_weight
的第0个条目。
另一个缺陷是,如果break
,那么coins[j].weight > i
是个好主意旧的代码可以break
当coin[j].weight <= i
和另一半的联合是错误的,即不可能制造重量i - coins[j].weight
的硬币。这在下面的测试用例中发生。
1
10 13
2
2 2
3 3
我们必须用2或3磅的硬币制造3磅。重量1被正确地确定为不可能。正确确定重量2是可能的。对于重量3,我们尝试重量2硬币,确定重量1不可能,并且在尝试重量3硬币之前
break
结果是代码错误地报告说不可能使权重为3。