标签:void cin algorithm space swa string get clu std
这道题乍一看明显是BFS , 但是怎么进行状态的转移是个问题,看了网上的思想,很多都是用hash来保存状态的,看他们都写了一百五十多行,我很害怕,看到有用map的,我醍醐灌顶,把网上的思想综合起来,我写了一个程序,虽然是飘过。。。。。
#include <iostream> #include <cstdio> #include <algorithm> #include <map> #include <queue> #include <string> #include <cstring> using namespace std; char stand[33] = { 11 ,12 ,13 ,14 ,15 ,16 ,17 ,1 , 21 ,22 ,23 ,24 ,25 ,26 ,27 ,1 , 31 ,32 ,33 ,34 ,35 ,36 ,37 ,1 , 41 ,42 ,43 ,44 ,45 ,46 ,47 ,1 , }; struct node { char map[32]; int step; node() { memset(map, 0, sizeof(map)); map[0] = map[8] = map[16] = map[24] = 1; step = 0; } }; queue <node> q; queue <node> null; map<string, int> m; map < string, int > nul; /*void put(node nod) { for (int i = 0; i < 32; i++) { if (i % 8 == 0) cout << endl; printf("%d ", nod.map[i]); } cout << endl; } */ int get_pos(int num,const node &nod) { for (int i = 0; i < 32; i++) { if (nod.map[i] == num) return i; } } int bfs() { while (!q.empty()) { node tmp = q.front(); q.pop(); bool f = true; for (int i = 0; i < 32; i++) { if (tmp.map[i] != stand[i]) { f = false; break; } } if (f) return tmp.step; m[tmp.map]++; for (int i = 0; i < 32; i++) { if (tmp.map[i] == 1 && (i % 8) && tmp.map[i-1] != 1 && tmp.map[i - 1] % 10 < 7) { int pos = get_pos(tmp.map[i - 1] + 1,tmp); if (pos % 8 == 0) continue; node new_nod = tmp; new_nod.step++; swap(new_nod.map[i], new_nod.map[pos]); if (!m[new_nod.map]) q.push(new_nod), m[new_nod.map]++; } } } return -1; } int main() { int t; cin >> t; while (t--) { q = null; m = nul; node nod; //put(nod); stand[32] = ‘\0‘; nod.map[32] = ‘\0‘; for (int i = 0; i < 4; i++) { for (int j = 0; j < 7; j++) { // scanf("%d", &nod.map[8 * i + j + 1]); } } nod.map[0] = nod.map[8] = nod.map[16] = nod.map[24] = 1; for (int i = 0; i < 4; i++) { for (int j = 0; j < 7; j++) { int tmp = 8 * i + j + 1; if (nod.map[tmp] == 11) swap(nod.map[tmp], nod.map[0]); if (nod.map[tmp] == 21) swap(nod.map[tmp], nod.map[8]); if (nod.map[tmp] == 31) swap(nod.map[tmp], nod.map[16]); if (nod.map[tmp] == 41) swap(nod.map[tmp], nod.map[24]); } } q.push(nod); m[nod.map]++; cout << bfs() << endl; } return 0; }
为了简化操作,我把二维的数组降为一维。
标签:void cin algorithm space swa string get clu std
原文地址:https://www.cnblogs.com/cuizhihui/p/10924597.html