代码不适用于所有可能性

时间:2017-10-15 21:46:23

标签: c++

问题如下: 基本上一个人正在种植橘子,只有一粒种子,只能生长2粒种子,首先是在 x 月后,第二粒是在 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;
}

1 个答案:

答案 0 :(得分: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);
    }
}