Hard math problem(递归)

描述

Xioumu was trapped by a mathematical puzzle recently.

He wrote the number 0,1,2 on the blackboard, and then he does lots of operations on them, in each operation, he took out the larger two numbers of the three every time, added the two numbers and wrote down the sum on the blackboard, and then wiped any one of the original three numbers. He needed to use a minimum times of operations to get a maximum number x. Now he needs your help.

输入

The first line is an integer T indicates the number of test cases.
Input contains several test cases.
For each test case, there is a number x (1<=x<=5*10^5) in a line.

输出

For each case, output the case number first. Then output the minimum number of operations. If he can’t get x, just output -1.

样例输入

3
2
6
13

样例输出

Case 1: 0
Case 2: 4
Case 3: 4

题意:现在有三个数字0,1,2每次只取其中最大的俩个数字相加产生一个数,于是现在有4个数,你可以任意的选择去掉一个数,一直重复…
输入一个目标数字,问你最少需要几步操作能够到达这个数字
想一下操作每次是由最大的俩个数x,y产生一个更大的数字z,但是你只能去掉一个数,那么x,y至少有一个留下来,并参与下一次的加法,也就是由x+z或者是y+z…重复…从结果倒着退回去,将一个数分成俩个数字,大的-小的等到更小的,小的-更小的=更更小的…如果最后一步x,y是由2和1组成的那么说明能够经过有限步到达给定的数字,画个图可以对照着理解一下
Hard math problem(递归)_第1张图片
给代码:

#include
using namespace std;
#define inf 0x3f3f3f3f
int x,y;

int sum;
int f(int x,int y){
 //   cout<<"x=: y=: "<
    sum++;
    if(x<2||y<1) return inf;
    else if(x==2&&y==1) return sum;

    if(x-y<y) f(y,x-y);
    else  f(x-y,y);
}
int main(){
    int t;
    scanf("%d",&t);
    for(int i=1;i<=t;i++){
        int k,mi=inf;
        scanf("%d",&k);
        y=k/2;
        for(y;y>0;y--){
            x=k-y;
            sum=0;
            if(y>x){
                swap(y,x);
            }
            int flag=f(x,y);
            if(flag<mi){
                mi=flag;
            }
        }
        if(k==2) mi=0;
        else if(mi>=inf) mi=-1;

        printf("Case %d: %d\n",i,mi);
    }
}

你可能感兴趣的:(C++)