2017-10-15 63 views
-1

工作中的問題如下: 基本上是一個傢伙是種植橘子和一個種子有隻能X個月後增長2種,一是和後X第二+ y。一旦它長大,他就種植它。我需要計算在N個月內有多少種子會增長,問題出在這個代碼上,我沒有得到所有的答案。我所知道的是,只有少數人才能得到答案,但我不能確定是否有更多的答案,而且我也無法知道哪些答案,而且我也不知道問題出在哪裏。代碼並不適用於所有的可能性

#include<iostream> 
long int xKelias(long int N, int x); //x route, counts all oranges assuming the route will be only x till the n from i giving point 
long int yKelias(long int N, int y); //same with the y 
//doing this just for sake of cleaner code 

int main() {  
    int x, y; 
    long int N; //months 
    long long int suma = 0; //total amount of oranges 

    std::cin >> x >> y >> N; 
    y = y + x; //simplifying 
    suma += xKelias(N, x) - 1; // adding the x route 
    bool yra = true; 
    while (yra) 
    { 
     yra = false; 
     for (int i = 0; i < xKelias(N, x); i++) 
     { 
      if (N - i*x > 0) 
      { 
       suma += yKelias(N - i*x, y) - 1;//y route from every other point of x route 
       yra = true; 
      } 
      for (int j = 1; j < yKelias(N, y); j++) 
      { 
       if ((N - i*x) - y*j > 0) 
       { 
        suma += xKelias((N - i*x) - y*j, x) - 1;// x route from every y route that is from x 
        yra = true; 
       }    
      } 
     } 
     N = N - y - x; // lowering N minimum amount and repeating 
    } 
    std::cout << suma << std::endl; 
    return 0; 
} 
long int xKelias(long int N, int x) { 
    long int suma = 0; 
    suma += N/x + 1; 
    return suma; 
} 
long int yKelias(long int N, int y) { 
    long int suma = 0; 
    suma += N/y + 1; 
    return suma; 
} 
+2

使用開發環境隨附的調試軟件逐步執行程序。留意這個程序做你不期望的事情,因爲這可能是一個錯誤。 – user4581301

回答

0

我不知道如果我理解這個問題,所以請糾正我,如果我錯了,也許這樣我可以找到另一種解決方案。無論如何,這是我得到的。我看到它的方式是你有一個本質遞歸的問題,所以我將從一個簡單的遞歸函數開始,然後尋找一個不會導致堆棧溢出的解決方案。

long int seeds_count(long int x, long int y, long int N) { 
    if(N < x) { 
     // There's no time for the seed to grow and give any new seeds so the result is zero. 
     return 0; 
    } else if(x <= N && N < x + y) { 
     // There is enough time for the seed to give one new seed but it's too little time for the other seed to appear - which is the '1' in the result. Also, the new seed may still have enough time give us a few other seeds - that's the recursive call to seeds_count. 
     return 1 + seeds_count(x, y, N - x); 
    } else { 
     // This case is a sum of the result from the previous case (because the first seed has enough time to appear and maybe to grow some other seeds), one more seed (the second seed that grew from the starting seed) and the number of seeds (if any) that grew from the second seed. 
     return 2 + seeds_count(x, y, N - x) + seeds_count(x, y, N - x - y); 
    } 
} 
+0

它的工作,謝謝! –

相關問題