题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1430
思路:由于只是8种颜色,所以标号就无所谓了,对起始状态重新修改标号为 12345678,对目标状态标号做相应的修改,先预处理出12345678到所有状态的路径,记录所有状态的pre值,直接输出即可。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 #include<string> 7 using namespace std; 8 9 struct Node{ 10 char str[11]; 11 Node(){}; 12 Node(char _str[]){ 13 for(int i=0;i<8;i++){ 14 str[i]=_str[i]; 15 } 16 } 17 }; 18 19 int fac[]={1,1,2,6,24,120,720,5040,40320}; 20 int Get_Hash(Node &p) 21 { 22 int val=0; 23 for(int i=0;i<8;i++){ 24 int cnt=0; 25 for(int j=0;j<i;j++){ 26 if(p.str[j]>p.str[i])cnt++; 27 } 28 val+=cnt*fac[i]; 29 } 30 return val; 31 } 32 33 void Move_A(Node &p) 34 { 35 reverse(p.str,p.str+8); 36 } 37 38 void Move_B(Node &p) 39 { 40 char ch=p.str[3]; 41 for(int i=3;i>=1;i--)p.str[i]=p.str[i-1]; 42 p.str[0]=ch; 43 ch=p.str[4]; 44 for(int i=4;i<=6;i++)p.str[i]=p.str[i+1]; 45 p.str[7]=ch; 46 } 47 48 void Move_C(Node &p) 49 { 50 swap(p.str[1],p.str[2]); 51 swap(p.str[5],p.str[6]); 52 swap(p.str[1],p.str[5]); 53 } 54 55 56 int pre[400000],ans[400000]; 57 bool mark[400000]; 58 59 void BFS() 60 { 61 queue<Node>que; 62 que.push(Node("12345678")); 63 memset(mark,false,sizeof(mark)); 64 mark[0]=true; 65 while(!que.empty()){ 66 Node p=que.front(); 67 que.pop(); 68 int p_val=Get_Hash(p); 69 Node q(p); 70 Move_A(q); 71 int q_val=Get_Hash(q); 72 if(!mark[q_val]){ 73 mark[q_val]=true; 74 pre[q_val]=p_val; 75 ans[q_val]='A'; 76 que.push(q); 77 } 78 q=p; 79 Move_B(q); 80 q_val=Get_Hash(q); 81 if(!mark[q_val]){ 82 mark[q_val]=true; 83 pre[q_val]=p_val; 84 ans[q_val]='B'; 85 que.push(q); 86 } 87 q=p; 88 Move_C(q); 89 q_val=Get_Hash(q); 90 if(!mark[q_val]){ 91 mark[q_val]=true; 92 pre[q_val]=p_val; 93 ans[q_val]='C'; 94 que.push(q); 95 } 96 } 97 } 98 99 char S[11],T[11]; 100 int SS[11]; 101 int main() 102 { 103 BFS(); 104 while(~scanf("%s%s",S,T)){ 105 for(int i=0;i<8;i++)SS[S[i]-'1']=i; 106 for(int i=0;i<8;i++)T[i]=SS[T[i]-'1']+'1'; 107 Node p=Node(T); 108 int val=Get_Hash(p); 109 string ss=""; 110 while(val){ 111 ss+=ans[val]; 112 val=pre[val]; 113 } 114 reverse(ss.begin(),ss.end()); 115 cout<<ss<<endl; 116 } 117 return 0; 118 } 119 120 121 122 123 124 125 126 127 128 129 130