二进制密码锁

 

题解:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     string init, result; // 要操作的,预期的
 7     string temp;         // 记录当前状态
 8     cin >> init >> result;
 9     int n = init.length(), res = 31; // 最多加30次
10     for (int i = 0; i < 2; ++i)
11     {
12         // 当前状态
13         temp = init;
14 
15         int next = i, times = 0;
16 
17         for (int j = 0; j < n; ++j)
18         {
19             if (next == 1)
20             {
21                 ///////////////////
22                 if (j > 0)
23                     temp[j - 1] ^= 1; //^1即实现取反的效果
24                 temp[j] ^= 1;
25                 if (j < n - 1)
26                     temp[j + 1] ^= 1;
27                 ///////////////////
28                 // 以上实现相邻3位取反(边缘为2位)
29 
30                 times++; // 操作次数加1
31             }
32             if (temp[j] == result[j]) // 若两位相同,则不用按下一位
33                 next = 0;
34             else // 若不同,则要按下一位
35                 next = 1;
36             if (temp == result) // 如果能达到预期结果
37             {
38                 res = min(res, times); // 记录最小操作数
39                 break;
40             }
41         }
42     }
43     if (res != 31)
44         cout << res;
45     else // 无法达到预期
46         cout << "impossible";
47 
48     return 0;
49 }

 

 

python代码:

  注意tmp的拷贝问题

 1 s1 = input()
 2 s2 = input()
 3 s1, s2 = list(s1), list(s2)
 4 # tmp = s1 #temp修改会导致s1也被修改
 5 # print(id(tmp), id(s1))
 6 n = len(s1)
 7 res = 31
 8 for i in range(2):
 9     # temp = s1.copy() #这样就不会修改原s1的值,因为temp和s1内存地址不同
10     temp = list(s1)  # 与上一行等价
11     next = i
12     times = 0
13     # print(temp)
14     for j in range(n):
15         if next == 1:
16             if j > 0:
17                 temp[j - 1] = '1' if temp[j - 1] == '0' else '0'
18             temp[j] = '1' if temp[j] == '0' else '0'
19             if j < n - 1:
20                 temp[j + 1] = '1' if temp[j + 1] == '0' else '0'
21             times += 1
22             # print(times, end='&')
23             # if times == 1:
24             # print(temp)
25             # print(s1)
26             # if times == 2:print(temp)
27             # if times == 3:print(temp)
28             # if times == 4:print(temp)
29 
30         if temp[j] == s2[j]:
31             next = 0
32         else:
33             next = 1
34         if temp == s2:
35             res = min(res, times)
36             break
37 if res != 31:
38     print(res)
39 else: print('impossible')

 

posted @ 2023-07-11 22:58  上原歩夢  阅读(69)  评论(0)    收藏  举报