2011-05-31 13 views
2

私はSPOJからPouring Waterを完成させました。しかし、システムはに間違った回答を与え続けます。しかし、どこが間違っているのか分からない。水を注ぐ、どこが間違っていますか?

ヒントを教えてください。テストケースも評価されています。

#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; 
     } 
    } 
} 

私のアルゴリズムは、まず、特殊な例ifelse ifelse ifを確認し、elseでメインの計算を行います。 elseの部分については、最初の変数から2番目の変数に流し込む関数を書いています。

答えて

3

ここはヒントです。これはあなたの利益のためのコーディング演習であるので、私はあなたに完全な答えを与えません。

あなたはあなたの答えを得るために任意の順序で組み合わせる必要があるかもしれない4つの操作があります。あなたの番号が21, 3, 15だとします。繰り返しをaにダンプするか、または15が入るまで、またはに入力してからbに流し続けて15になるまでダンプしてください。現在の操作では、一連の操作が試行されます。あなたは何とかを試してみる必要があります。から一番良いものを選んでください。

+0

私は 'int fromA = countFromA(a、b、c);を試しました。 int fromB = countFromA(b、a、c); '最初のものは 'a、b'で、2番目のものは' b、a'です。 –

+0

@Dante Jiang: 'countFromA'は' b_in'が 'a'をすべてダンプした後で探している答えに巻き込まれても気付かないでしょう。 – btilly

+0

あなたは私に失敗のケースを教えてください。 –