题解 | #玛雅人的密码#
玛雅人的密码
https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0
#include <iostream> #include <queue> #include <unordered_map> #include<algorithm> using namespace std; int main() { int n; while (cin >> n) { // 注意 while 处理多个 case string str; cin >> str; if (str.find("2012") != -1) { cout << 0 << endl; continue; } bool flag = false; unordered_map<string, int> map; queue<string> qu; map[str] = 0; qu.push(str); while (!qu.empty()) { string s = qu.front(); qu.pop(); for (int i = 0; i < n - 1; i++) { string s1 = s; swap(s1[i], s1[i + 1]); if (map.count(s1) == 0) { map[s1] = map[s] + 1; qu.push(s1); } if (s1.find("2012") != -1) { flag = true; cout <<map[s1]<<endl; break; } } if(flag) break; } } } // 64 位输出请用 printf("%lld")