呵呵,这个题目有点意思,要用bfs:
/* ID: qq104801 LANG: C++ TASK: msquare */ #include <iostream> #include <fstream> #include <queue> #include <set> #include <string> #include <algorithm> using namespace std; struct node{ int d; string st,str; node(string _st,string _str,int _d) {st=_st;str=_str;d=_d;} }; string end=""; set<string> ss; queue<node> q; node bfs() { string x="12345678"; if(end==x)return node("","",0); q.push(node(x,"",0)); ss.insert(x); while(!q.empty()) { node curr=q.front(); q.pop(); string c=curr.st; string a(c.rbegin(),c.rend()); if(a==end) return node(a,curr.str+"A",curr.d+1); if(!ss.count(a)) { ss.insert(a); q.push(node(a,curr.str+"A",curr.d+1)); } string b(c[3]+c.substr(0,3)+c.substr(5)+c[4]); if(b==end)return node(b,curr.str+"B",curr.d+1); if(!ss.count(b)) { ss.insert(b); q.push(node(b,curr.str+"B",curr.d+1)); } swap(c[1],c[2]);swap(c[1],c[5]);swap(c[1],c[6]); if(c==end)return node(c,curr.str+"C",curr.d+1); if(!ss.count(c)) { ss.insert(c); q.push(node(c,curr.str+"C",curr.d+1)); } } } void test() { freopen("msquare.in","r",stdin); freopen("msquare.out","w",stdout); char c; for(int i=0;i<8;i++){ cin>>c; end+=c; } node n=bfs(); cout<<n.d<<endl<<n.str<<endl; } int main () { test(); return 0; }
test data
USACO Training Grader Results 8 users online CHN/4 KGZ/1 MYS/1 SGP/1 TTO/1 USER: cn tom [qq104801] TASK: msquare LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.019 secs, 3524 KB] Test 2: TEST OK [0.003 secs, 3524 KB] Test 3: TEST OK [0.016 secs, 3524 KB] Test 4: TEST OK [0.005 secs, 3524 KB] Test 5: TEST OK [0.046 secs, 4052 KB] Test 6: TEST OK [0.092 secs, 4712 KB] Test 7: TEST OK [0.159 secs, 5636 KB] Test 8: TEST OK [0.270 secs, 6032 KB] All tests OK. YOUR PROGRAM ('msquare') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations. Here are the test data inputs: ------- test 1 ---- 2 6 8 4 5 7 3 1 ------- test 2 ---- 1 2 3 4 5 6 7 8 ------- test 3 ---- 6 7 4 1 8 5 2 3 ------- test 4 ---- 5 1 2 4 3 7 8 6 ------- test 5 ---- 6 1 5 4 3 2 7 8 ------- test 6 ---- 4 1 2 3 5 8 7 6 ------- test 7 ---- 3 4 2 1 5 6 7 8 ------- test 8 ---- 4 3 1 2 5 6 7 8 Keep up the good work! Thanks for your submission!