解题思路

  1. 题目要求将两个数字 通过按钮操作转换成目标数字
  2. 有两种操作:
    • 红色按钮:两个数字同时加1
    • 蓝色按钮:两个数字同时乘2
  3. 使用DFS搜索所有可能的操作序列,找到最短的有效序列
  4. 剪枝条件:
    • 如果当前数字超过目标数字,则无效
    • 如果当前步数超过已知最小步数,则停止搜索
    • 如果只有一个数字达到目标而另一个没有,则无效

代码

#include <iostream>
using namespace std;

const int INF = 999999;
int minSteps = INF;

void dfs(int a, int b, int A, int B, int step) {
    // 剪枝条件
    if (a > A || b > B || step >= minSteps) return;
    if ((a == A && b != B) || (b == B && a != A)) return;
    
    // 找到解
    if (a == A && b == B) {
        minSteps = min(minSteps, step);
        return;
    }
    
    // 尝试两种操作
    dfs(a * 2, b * 2, A, B, step + 1);  // 蓝色按钮
    dfs(a + 1, b + 1, A, B, step + 1);  // 红色按钮
}

int main() {
    int a, b, A, B;
    cin >> a >> b >> A >> B;
    
    dfs(a, b, A, B, 0);
    
    cout << (minSteps == INF ? -1 : minSteps) << endl;
    return 0;
}
import java.util.*;

public class Main {
    static final int INF = 999999;
    static int minSteps = INF;
    
    static void dfs(int a, int b, int A, int B, int step) {
        // 剪枝条件
        if (a > A || b > B || step >= minSteps) return;
        if ((a == A && b != B) || (b == B && a != A)) return;
        
        // 找到解
        if (a == A && b == B) {
            minSteps = Math.min(minSteps, step);
            return;
        }
        
        // 尝试两种操作
        dfs(a * 2, b * 2, A, B, step + 1);  // 蓝色按钮
        dfs(a + 1, b + 1, A, B, step + 1);  // 红色按钮
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int A = sc.nextInt();
        int B = sc.nextInt();
        
        dfs(a, b, A, B, 0);
        
        System.out.println(minSteps == INF ? -1 : minSteps);
    }
}
def dfs(a, b, A, B, step, min_steps):
    # 剪枝条件
    if a > A or b > B or step >= min_steps[0]:
        return
    if (a == A and b != B) or (b == B and a != A):
        return
    
    # 找到解
    if a == A and b == B:
        min_steps[0] = min(min_steps[0], step)
        return
    
    # 尝试两种操作
    dfs(a * 2, b * 2, A, B, step + 1, min_steps)  # 蓝色按钮
    dfs(a + 1, b + 1, A, B, step + 1, min_steps)  # 红色按钮

a, b, A, B = map(int, input().split())
min_steps = [float('inf')]  # 使用列表存储最小步数,便于在递归中修改

dfs(a, b, A, B, 0, min_steps)

print(-1 if min_steps[0] == float('inf') else min_steps[0])

算法及复杂度

  • 算法:深度优先搜索(DFS)+ 剪枝
  • 时间复杂度: - 每步有两种选择,但实际因为剪枝会小很多
  • 空间复杂度: - 递归调用栈的深度, 为最小操作步数