c++ - 你能解释一下问题出在哪里吗?[SPOj-练习]
问题描述
我的意思是说老实说我找不到问题,而且这段代码似乎很容易写,我没有被接受。也许您可以帮助我并找到答案,因为老实说我不知道。我正在尝试在 SPOJ 上进行此练习:https ://www.spoj.com/problems/PIGBANK/ 。我将非常感谢您对我的方法中的错误进行任何解释。
#include <iostream>
using namespace std;
void piggyBank(int, int);
int sumAll(int *,int, int);
/* SUMMARY
We need to find the smallest value available in the piggy bank
*/
int main()
{
int t = 0, e = 0, f = 0;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> e >> f;
piggyBank(e, f);
}
return 0;
}
void piggyBank(int weightEmpty, int weightFull)
{
int coinsAmount = 0, *coinValue, *coinWeight, totalWorth = 0, remainingWeight = weightFull - weightEmpty, smallestValPos = 0;
cin >> coinsAmount;
coinValue = new int[coinsAmount];
coinWeight = new int[coinsAmount];
// getting all the coins and weights in the piggy bank
for (int i = 0; i < coinsAmount; i++)
{
cin >> coinValue[i] >> coinWeight[i];
if ((remainingWeight / coinWeight[smallestValPos] > remainingWeight / coinWeight[i]) && (remainingWeight % coinWeight[i] == 0)) smallestValPos = i;
}
// we need to check how many coinValue[smallestValPos] are there inside piggy bank
if(remainingWeight%coinWeight[smallestValPos] == 0)totalWorth = remainingWeight / coinWeight[smallestValPos] * coinValue[smallestValPos];
// output according to the excercise's constraints
if (totalWorth == 0) cout << "This is impossible.\n";// << endl;
else cout << "The minimum amount of money in the piggy-bank is " << totalWorth << ".\n"; //<< endl;
}
int sumAll(int *tab,int start, int end)
{
int sum = 0;
for (int i = start; i < end; i++)
{
sum += tab[i];
}
return sum;
}
来自 SPOJ 的样本输入:
3 10 110 2 1 1 30 50 10 110 2 1 1 50 30 1 6 2 10 3 20 4
SPOJ 的示例输出:
存钱罐中的最低金额是 60。存钱罐中的最低金额是 100。这是不可能的。
解决方案
在您的解决方案中,您只考虑每个重量硬币的最小价值,但如果这不增加确切的重量,您还必须使用其他硬币来匹配重量。这是练习变得有趣的时候。
当然,正如评论中所提到的,当你可以使用容器时,为什么会有内存泄漏?
推荐阅读
- eclipse - Eclipse 项目文件与以前版本的 Eclipse 兼容吗?
- python - 如何使用 python groupby 从给定的文本文件中拆分测试名称和日志详细信息
- intellij-idea - IntelliJ 的嵌入式终端无法正确加载我的鱼壳配置
- angular - NativeScript - WebView 内的 Angular HTML 组件
- sql - 从字符串转换日期和/或时间时 C# 转换失败
- c++ - 在键盘箭头键上禁用 QSlider 的 valueChanged
- jquery - 嵌入式时间轴中的多个 Twitter 提要不再起作用
- suse - 在 SUSE Linux ESS 12 SP3 上配置 XRDP 时需要帮助
- testing - Jmeter postProcessor 在所有 http 请求完成后仅执行一次
- angular - 如何使用 Jasmine 在 Angular 单元测试中模拟 window.screen.width