A*
https://www.luogu.org/problemnew/show/P1379
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <cmath> 5 #include <map> 6 #include <queue> 7 #include <algorithm> 8 using namespace std; 9 #define ll long long 10 const int maxn=1e6+10; 11 const int ci=1e6; 12 13 struct node 14 { 15 int a[9],pos; 16 }; 17 18 struct rec 19 { 20 ///g:from source to this condition(actual) 21 ///h:from this condition to destination(predict) 22 node d; 23 int g,tot; 24 bool operator<(const rec &b) const 25 { 26 ///绝对不能仅仅是b.tot<tot 27 if (b.tot==tot) 28 return b.g<g; 29 return b.tot<tot; 30 } 31 }; 32 priority_queue<rec> st; 33 34 int f[][5]={ 35 {2,1,3}, 36 {3,0,2,4}, 37 {2,1,5}, 38 {3,0,4,6}, 39 {4,1,3,5,7}, 40 {3,2,4,8}, 41 {2,3,7}, 42 {3,4,6,8}, 43 {2,5,7}, 44 }; 45 46 int dest[]={1,2,3,8,0,4,7,6,5}; 47 48 map<ll,int> m; 49 50 ll cal(int a[]) 51 { 52 int i; 53 ll j=1,sum=0; 54 for (i=0;i<9;i++) 55 { 56 sum+=j*a[i]; 57 j*=9; 58 } 59 return sum; 60 } 61 62 int predict(int a[]) 63 { 64 int sum=0,i; 65 for (i=0;i<9;i++) 66 sum+=a[i]!=dest[i]; 67 if (sum==0) 68 sum=1; 69 return sum-1; 70 } 71 72 void pr(int a[]) 73 { 74 int i; 75 for (i=0;i<9;i++) 76 { 77 printf("%d ",a[i]); 78 if (i%3==2) 79 printf("\n"); 80 } 81 printf("\n"); 82 } 83 84 int main() 85 { 86 char s[10]; 87 int i,g,pos; 88 ll sum,sumdest; 89 node d; 90 91 scanf("%s",s); 92 for (i=0;i<9;i++) 93 { 94 d.a[i]=s[i]-48; 95 if (d.a[i]==0) 96 d.pos=i; 97 } 98 sum=cal(d.a); 99 m[sum]=0; 100 sumdest=cal(dest); 101 if (sum==sumdest) 102 { 103 printf("0"); 104 return 0; 105 } 106 107 st.push({d,0,predict(d.a)}); 108 while (!st.empty()) 109 { 110 d=st.top().d; 111 // pr(d.a);/// 112 g=st.top().g; 113 st.pop(); 114 pos=d.pos; 115 for (i=1;i<=f[pos][0];i++) 116 { 117 swap(d.a[pos],d.a[f[pos][i]]); 118 sum=cal(d.a); 119 if (sum==sumdest) 120 { 121 printf("%d",g+1); 122 return 0; 123 } 124 ///遇到比之前好的,则修改! 125 if (m.find(sum)==m.end() || m[sum]<g+1) 126 { 127 m[sum]=g+1; 128 d.pos=f[pos][i]; 129 st.push({d,g+1,g+1+predict(d.a)}); 130 } 131 swap(d.a[pos],d.a[f[pos][i]]); 132 } 133 } 134 return 0; 135 } 136 /* 137 123804765 138 139 023184765 140 141 021345678 142 143 201534786 144 145 201534786 146 19 147 */