整数变换问题

#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;

const int MAX = 50;
int n, m;
int x[MAX];
int bestx[MAX];

int f(int i, int n)
{
    if(i==1)
        return n*3;
    else
        return n/2;
}

int k;  //搜索深度,逐步加深
bool found = false;
bool backtrack(int dep, int n)
{
    if(dep > k)
        return false;
    else
    {
        for(int i=1; i<=2; i++)
        {
            int temp = f(i, n);
            x[dep] = i;
            if(temp == m || backtrack(dep+1, temp))
            {
                found = true;
                for(int j=1; j<=k; j++)
                    bestx[j] = x[j];
                return true;
            }
            x[dep] = 0;
        }
    }
    return false;
}

void search()
{
    k = 1;
    while(!backtrack(1, n))
    {
        k++;
        memset(x, 0, sizeof(x));
        memset(bestx, 0, sizeof(bestx));
    }
}

int main()
{
    ifstream fin("整数变换.txt");
    cout << "输入正整数n:";
    fin >> n;  cout << n;
    cout << "\n输入正整数m:";
    fin >> m;  cout << m << endl;

    search();
    if(found)
    {
        cout << n << "变为" << m << "最少的变换次数为:" << k << endl;
        cout << "变换过程为:";
        for(int i=1; i<=k; i++)
            if(bestx[i] == 1)
                cout << 'f';
            else 
                cout << 'g';
    }
    else
        cout << "变换失败!\n";
    cout << endl << endl;
    return 0;
}

这里写图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值