其他分享
首页 > 其他分享> > 二进制密码锁

二进制密码锁

作者:互联网

当某一个按钮状态确定后,它的下一个按钮按与不按取决于这一个与目标状态是否一致,所以后续所有按钮其实都只取决于第一个按钮。

枚举共两种情况:第一个按钮按(用1标记),第一个按钮不按(用0标记)

最多次数为30次,故最终结果res初始化为31,用于判断impossible的情况

注意:首尾按钮取反需单独讨论,只影响单边

#include <iostream>
#include <string>
#include <bitset>
#include <algorithm>
using namespace std;
int main () {
    string str;
    cin >> str;
    // 期望状态
    bitset<30> target(str);
    cin >> str;
    // 起始状态
    bitset<30> recent(str);
    int n = str.size(), res = 31;
    bitset<30> temp;
    // 最左边按下或不按下,0为不按下,1为按下
    for (int i = 0; i < 2; i++) {
        // 当前状态
        temp = recent;
        // next表示2当前按钮是否按下
        int next = i, times = 0;
        // 遍历所有按钮
        for (int j = 0; j < n; j++) {
            // 该按钮需按下
            if (next == 1) {
                // 取反
                if (j > 0) temp.flip(j - 1);
                temp.flip(j);
                if (j < n - 1 ) temp.flip(j + 1);
                times++;
            }
            // 如果相同,则不按下一个按钮,否则按下下一个按钮
            if (temp[j] == target[j]) next = 0;
            else next = 1;
            if (temp == target) {
                res = min(res, times);
                break;
            }
        }
    }
    if (res != 31) cout << res;
    else cout << "impossible";
    return 0;
}

标签:temp,二进制,res,next,int,str,按钮,密码锁
来源: https://blog.csdn.net/yzlmhzz/article/details/123218437