代码不适用于所有可能性



问题如下:基本上,一个人在种植橙子,一颗种子只能长出两颗种子,第一颗是在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;
}

我不确定我是否理解这个问题,所以如果我错了,请纠正我,也许我可以找到另一个解决方案。不管怎样,这是我得到的。在我看来,你有一个本质上是递归的问题,所以我会从一个简单的递归函数开始,然后寻找一个不会导致堆栈溢出的解决方案。

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

相关内容

最新更新