Hard math problem(递归)

这是一道数学与算法问题,题目描述了如何从数字0,1,2开始,每次选取两个最大数相加并替换其中一个,以求达到目标数字所需的最小操作次数。对于给定的目标数字,需要找出是否可能通过这种方式到达,以及需要多少次操作。样例输入和输出展示了不同测试用例的结果。" 88868352,427261,Oracle XML处理:XPath与特殊字符解析,"['数据库', 'Oracle', 'XML处理', 'XPath查询', '数据存储']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

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组成的那么说明能够经过有限步到达给定的数字,画个图可以对照着理解一下
在这里插入图片描述
给代码:

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
int x,y;

int sum;
int f(int x,int y){
 //   cout<<"x=: y=: "<<x<<" "<<y<<endl;
    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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值