九度OJ 1482:瑪雅人的密碼
阿新 • • 發佈:2017-08-04
清華 sizeof swap name substr wap 如果 found www
- 題目描述:
-
瑪雅人有一種密碼,如果字符串中出現連續的2012四個數字就能解開密碼。給一個長度為N的字符串,(2=<N<=13)該字符串中只含有0,1,2三種數字,問這個字符串要移位幾次才能解開密碼,每次只能移動相鄰的兩個數字。例如02120經過一次移位,可以得到20120,01220,02210,02102,其中20120符合要求,因此輸出為1.如果無論移位多少次都解不開密碼,輸出-1。
- 輸入:
-
輸入包含多組測試數據,每組測試數據由兩行組成。
第一行為一個整數N,代表字符串的長度(2<=N<=13)。
第二行為一個僅由0、1、2組成的,長度為N的字符串。
- 輸出:
-
對於每組測試數據,若可以解出密碼,輸出最少的移位次數;否則輸出-1。
- 樣例輸入:
-
5 02120
- 樣例輸出:
-
1
- 來源:
- 2012年清華大學計算機研究生機試真題
思路:
hash + BFS。
BFS的題目經常搭配著hash,BFS題目最終要的一點是”剪枝“,假如不適當的剪枝可能會超時,這裏用hash數組進行剪枝是一個好的方法。
本題中hash采用三進制——因為字符串中只有0、1、2,對所有的字符串狀態進行標記。
和這個有些相似的題目有CCF 201604-4 遊戲,也采用了狀態標記的方法進行剪枝。
#include <iostream> #include <stdio.h> #include <string> #include <math.h> #include <deque> #include <memory.h> using namespace std; string str; int N; bool visited[1600000]; bool match(const string &str1) { for(int i = 0; i <= N-4; i ++) { if(str1.substr(i, 4) == "2012") return true; } return false; } int hash_func(string cur) { int res = 0; for(int i = 0; i < N; i ++) res = res*3+cur[i]-‘0‘; return res; } int main() { while(scanf("%d", &N) != EOF) { cin >> str; memset(visited, 0, sizeof(visited)); deque<string> record; record.push_back(str); int cur_lel = 1, nxt_lel = 0, ret = 0; bool found = false; while(!record.empty()) { string cur = record.front(); record.pop_front(); cur_lel --; if(match(cur)) { found = true; cout << ret << endl; break; } for(int i = 0; i < N-1; i ++) { swap(cur[i], cur[i+1]); int hash_val = hash_func(cur); if(!visited[hash_val]) { visited[hash_val] = true; record.push_back(cur); nxt_lel ++; } swap(cur[i], cur[i+1]); } if(cur_lel == 0) { cur_lel = nxt_lel; nxt_lel = 0; ret ++; } } if(!found) cout << -1 << endl; } return 0; }
九度OJ 1482:瑪雅人的密碼