나는 사용자가 3 개의 숫자 인 a, b, c
을 입력하는 작업을 해결하고 있었다. 목표는 c
a
및 b
의 합계를 얻을 수 있는지 확인하는 것입니다. 각 단계에서 a
을 b
에 추가하고 b
을 a
에 추가 할 수 있습니다. 입력 한 숫자로 가능한지 알아야합니다. 입력 한 숫자는 0
과 10^18
사이입니다. 아래는 재귀를 사용하여 작성한 코드입니다. a=4 b=6 c=38
에 대한 작업을 해결재귀를 사용하는 C 프로그램은 최적화되고 고정 될 필요가있다.
예 :
a=4 b=10
a=14 b=10
a=14 b=24
a=38 b=24 print YES
이
내 아래 코드는하지만 낮은 숫자 아니라 그 일을 내가 생각하는 나는 더 큰 것을 가진 전투를 잃고있다. 숫자 ... 나는 어떤 부분이 무엇을하고 있는지에 대한 몇 가지 코멘트를 덧붙였다.
도움이 필요한 것은 더 잘 작동하고 더 빨리 작동해야하며 더 최적화하는 방법을 알지 못합니다.
//the function that I'm using
int task(long long int a, long long int b, long long int c, long long int d, int p)
{ //a, b and c are long long integers that are submited by the user, d is the sum of
//the unchanged a and b, and p is a flag
if(!a && !b && c) return 0; //0+0 will never get to 1
if(c==d) return 1; //if I get with c to d, it is confirmed yes,
//did the math with a pen :)
if(c<d || c<=0) // I thought this is a nice case to stop
{
return 0;
}
if(p==1)
{
if(a>c) return 0; //if the flag p is one, that means i changed a,
//so compare a
}
if(p==2)
{
if(b>c) return 0; //if p is two, i changed b so compare b
}
if(c-d>0) return task(a+b, b, c-b, d, 1)||task(a, b+a, c-a, d, 2);
//recursion call with OR operator so every step is checked
}//one part is a=a+b b=b c=c-b, i decrement c so fewer steps are needed,
//the other part is when i add a to b
int main()
{
long long int a,b,c;
scanf("%I64d%I64d%I64d",&a,&b,&c); //scaning
int p; //the flag for the first numbers
if(a>b) p=1; //i dont know if i need this step at all xD
else p=2; //but to make sure
if((a==1 || b==1) && c) printf("YES"); //a=1 b=1 and c>=1 means i can get to c,
//even with a+b+b+b..
else if(a==c || b==c) printf("YES"); //if one of the numbers are already same
//with c, no need to check
else if(task(a,b,c,a+b,p)) printf("YES"); //if the function returns 1, print YES
else printf("NO"); //or print NO
return 0;
}
알고리즘 개선에 더 집중할 것입니다. 아마도 반복문 대신 반복문으로 바꾸는 데 사용할 수있는 숫자 이론 원리가있을 것 같습니다. 동적 프로그래밍 (Dynamic Programming)을 요구할 수도 있습니다. – Daniel
@ 갤 러니 닉 a와 b의 배수가있는 c를 찾을 수 있습니까? 아니면 c가 a, b, a + b, a + a + b, a + a + b + b, a + a + a + b + b 등? –
@George Houpis, 아니오 n x a + m x b가 아닙니다.이 질문은 최근에 트리 재귀로 요청되었지만 아직 찾을 수 없습니다. –