【发布时间】:2020-04-30 13:10:54
【问题描述】:
我的意思是说我真的找不到问题,而且这段代码似乎很容易编写,但我没有被接受。也许您可以帮助我并找到答案,因为老实说我不知道。我正在尝试在 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。 这是不可能的。
【问题讨论】:
-
你甚至不能说明为什么它不被接受?
-
我得到错误的答案作为信息
-
输入、预期输出和实际输出是什么?
-
OT:您的代码似乎正在泄漏内存。也许切换到 std::vector 会有所帮助。
-
这是一个示例测试用例
1 0 7 2 3 3 4 4。你的算法打印This is impossible.正确答案是The minimum amount of money in the piggy-bank is 7.