Each 2x4 character array, with three different operations, requires minimal manipulation, from "12345678", to the target character, to the minimum number of steps, and to the sequence of operations.
The use of the C + + class library is still not well-acquainted.
/*id:modengd1prog:msquarelang:c++*/#include <iostream> #include <stdio.h> #include <queue># Include <map> #include <string>using namespace std;struct node{int step; string Sta,ans;}; map<string,bool> vis;void OpA (node &n) {n.step++; N.ans.push_back (' A '); for (int i=0;i<4;i++) {swap (n.sta[i],n.sta[i+4]); }}void OpB (node &n) {n.step++; N.ans.push_back (' B '); Char temp=n.sta[3]; for (int i=3;i>0;i--) {n.sta[i]=n.sta[i-1]; } n.sta[0]=temp; TEMP=N.STA[7]; for (int i=7;i>4;i--) {n.sta[i]=n.sta[i-1]; } n.sta[4]=temp;} void OpC (node &n) {n.step++; N.ans.push_back (' C '); Char temp=n.sta[1]; N.STA[1]=N.STA[5]; N.STA[5]=N.STA[6]; N.STA[6]=N.STA[2]; N.sta[2]=temp;} void BFS (string target) {queue<node> Q; Node now; Now.sta= "12348765"; Now.step=0;now.ans= ""; Vis[now.sta]=true; Q.push (now); while (! Q.empty ()) {nodeNext Node &N=next; Now=q.front (); Q.pop (); if (now.sta==target) {cout<<now.step<<endl<<now.ans<<endl; Return } Next=now; OpA (N); if (!vis[next.sta]) {Q.push (next); Vis[next.sta]=true; } Next=now; OpB (N); if (!vis[next.sta]) {Q.push (next); Vis[next.sta]=true; } Next=now; OpC (N); if (!vis[next.sta]) {Q.push (next); Vis[next.sta]=true; }}}int Main () {freopen ("msquare.in", "R", stdin); Freopen ("Msquare.out", "w", stdout); string target; Char ch; for (int i=0;i<8;i++) {scanf ("%c", &ch); Target.push_back (CH); GetChar (); } swap (target[5],target[6]);//The topic is in accordance with the clockwise clock, and I press from top to bottom, from left to right swap (target[7],target[4]); BFS (target); return 0;}
Usaco Magic Squares