题解/算法 {100159. 使 X 和 Y 相等的最少操作次数}

本文介绍了如何使用广度优先搜索(BFS)算法解决LeetCode题目,最少操作次数使X和Y相等。关键在于确定有效节点范围和优化搜索过程,避免不必要的深度搜索。
摘要由CSDN通过智能技术生成

题解/算法 {100159. 使 X 和 Y 相等的最少操作次数}

@LINK: https://leetcode.cn/problems/minimum-number-of-operations-to-make-x-and-y-equal/;

很難想到 其實直接BFS就可以…
是因為他的BFS層數很小嗎? 錯誤, 比如X=1, Y=10000 此時你只能執行X ++操作, 即BFS樹深度是1e4級別;
深度這麼大 顯然樹的規模是非常大的, 但本題非常特別: 她不會涉及到負數 而且所有合法的節點 其實就是[1, max(X,Y) + 11]這些數 (+11的原因是: 比如X += k到達一個5/11的倍數 然後執行/5或/11後 變成Y); 也就是 超過這個範圍的數 一定不會是答案路徑上的點, 因此 一共也就1e4個點 (n個點的BFS 時間是O(4(分支數)*n));

int minimumOperationsToMakeEqual(int X, int Y) {
    {
        int Ma = max(X,Y) + 11;
        static int Dist[ 20004];
        memset( Dist, -1, sizeof(Dist[0]) * Ma);
        using T_ = int;
        queue< T_> que;
        const T_ start = X, target = Y;
        que.push( start);  Dist[ start] = 0;
        while( !que.empty()){
            auto cur = que.front();  que.pop();
            if( cur == target){
                return Dist[target];
                break;
            }

            if( cur%5 == 0){
                auto nex = cur / 5;
                if( Dist[nex] == -1){ Dist[nex]=Dist[cur]+1; que.push( nex);}
            }
            if( cur%11 == 0){
                auto nex = cur / 11;
                if( Dist[nex] == -1){ Dist[nex]=Dist[cur]+1; que.push( nex);}
            }
            if( cur < Ma){
                auto nex = cur + 1;
                if( Dist[nex] == -1){ Dist[nex]=Dist[cur]+1; que.push( nex);}
            }
            if( cur > 1){
                auto nex = cur - 1;
                if( Dist[nex] == -1){ Dist[nex]=Dist[cur]+1; que.push( nex);}
            }
        }
    }
    return -1;
}
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值