c++ - 倒水,哪里出了问题?

标签 c++ algorithm

我已经完成了Pouring Water来自 SPOJ。然而,系统总是给出错误的答案。但我找不到哪里出了问题。

请给点提示。测试用例也受到赞赏。

#include <iostream>

int countFromA (int a, int b, int c);

int main() {
    int t;
    std::cin>>t;
    std::cin.ignore(5, '\n'); // SPOJ error: iostream limit
    while (t--) {
        int a, b, c;
        std::cin>>a>>b>>c;
        if (c == 0) {
            std::cout<<"0"<<std::endl;
        }
        else if (a == c || b == c) {
            std::cout<<"1"<<std::endl;
        }
        else if ((a < c && b < c) || (a == b)) {
            std::cout<<"-1"<<std::endl;
        }
        else {
            int fromA = countFromA (a, b, c);
            int fromB = countFromA (b, a, c);
            int result;
            if (fromA == -1) {
                result = fromB;
            }
            else if (fromB == -1) {
                result = fromA;
            }
            else if (fromA <= fromB) {
                result = fromA;
            }
            else {
                result = fromB;
            }
            std::cout<<result<<std::endl;
        }
    }
}

int countFromA (int a, int b, int c) {
    int times = 0;
    int a_in = 0;
    int b_in = 0;
    // fill a
    a_in = a;
    times++;
    while (true) {
        // a->b & test
        if (a_in > (b - b_in)) {
            a_in = a_in - (b - b_in);
            b_in = b;
            times++;
            if (a_in == c) {
                return times;
            }
        }
        else {
            b_in = b_in + a_in;
            a_in = 0;
            times++;

答案:应该在此处添加测试。我是在 a > b 的假设下进行编码的,当重用它时,我忘记了。

        }
        // fill a / empty b
        if (b_in == b) {
            b_in = 0;
        }
        else {
            a_in = a;
        }
        times++;
        // finish
        if (a_in == b - b_in) {
            return -1;
        }
    }
}

我的算法首先检查特殊情况if else if else if,然后在else中进行主要计算>。对于 else 部分,我编写了一个函数来从第一个变量倒入第二个变量。

最佳答案

这里有一个提示。由于这是为了您的利益而进行的编码练习,因此我不会给您完整的答案。

您可能需要按任意顺序组合 4 种不同的操作才能得到答案。假设您的号码是 21, 3, 15。您需要查看将 b 重复转储到 a 中,直到其中包含 15,或者填充 a,继续将其倒入b,然后倾倒b,直到剩下15。您当前的操作仅尝试单个操作序列。您需要以某种方式从头开始尝试两者,然后选择最好的一个。

关于c++ - 倒水,哪里出了问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6186301/

相关文章:

c++ - main.obj : fatal error LNK1143: invalid or corrupt file: no symbol for COMDAT section 0x6

c++ - 返回数组的一维?

c++ - 使用opencv跟踪多个人体头部

algorithm - 找到条纹线的角度/旋转角度

c++ - 这个for循环的运行时间复杂度是多少

c++ - vc++ 应用程序中的看门狗

c - 感知器学习算法不收敛到 0

java - 找到列表中最接近的数字

c# - 基于百分比加权的选择

c++ - std::string 的串联引用是安全的吗?