标签:should esc print href astar enter alt 返回 stream
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 130000/65536 K (Java/Others)
Total Submission(s): 3449 Accepted Submission(s): 753
1 //2017-09-23 2 #include <iostream> 3 #include <cstdio> 4 #include <algorithm> 5 #include <cmath> 6 #include <map> 7 8 using namespace std; 9 10 const int INF = 0x3f3f3f3f; 11 int a[10][10], target, postion[10], b[10], d[10000], sx, sy, deep; 12 bool ok; 13 map<int, bool> vis; 14 char dir[4] = {‘d‘, ‘l‘, ‘r‘, ‘u‘}; 15 int dx[4] = {1, 0, 0, -1};//分别对应上下左右四个方向 16 int dy[4] = {0, -1, 1, 0}; 17 int kase; 18 19 int Astar() 20 { 21 int h = 0; 22 for(int i = 1; i <= 3; i++) 23 for(int j = 1; j <= 3; j++) 24 if(a[i][j]!=0) 25 { 26 int num = a[i][j]; 27 int nx = (postion[num]-1)/3; 28 int ny = (postion[num]-1)%3; 29 h += (abs(i-nx-1)+abs(j-ny-1)); 30 } 31 return h; 32 } 33 34 int toInt()//把矩阵转换为int型数字 35 { 36 int res = 0; 37 for(int i = 1; i <= 3; i++) 38 for(int j = 1; j <= 3; j++) 39 res = res*10+a[i][j]; 40 return res; 41 } 42 43 void IDAstar(int x, int y, int pre, int step) 44 { 45 if(ok)return ; 46 int h = Astar(); 47 if(!h && toInt()==target)//找到答案 48 { 49 printf("Case %d: %d\n", ++kase, step); 50 for(int i = 0; i < step; i++) 51 printf("%c", dir[d[i]]); 52 printf("\n"); 53 ok = 1; 54 return ; 55 } 56 if(step+h>deep)return ;//现实+理想<现状,则返回,IDA*最重要的剪枝 57 int now = toInt(); 58 //if(vis[now])return ;//如果状态已经搜过了,剪枝,避免重复搜索 59 //vis[now] = true; 60 for(int i = 0; i < 4; i++) 61 { 62 if(i+pre == 3)continue; 63 int nx = x+dx[i]; 64 int ny = y+dy[i]; 65 if(nx>=1&&nx<=3&&ny>=1&&ny<=3) 66 { 67 d[step] = i; 68 swap(a[x][y], a[nx][ny]); 69 IDAstar(nx, ny, i, step+1); 70 swap(a[x][y], a[nx][ny]); 71 d[step] = 0; 72 } 73 } 74 return; 75 } 76 77 char str1[20], str2[20]; 78 79 int main() 80 { 81 int T; 82 scanf("%d", &T); 83 char ch; 84 kase = 0; 85 while(T--) 86 { 87 ok = false; 88 deep = 0; 89 int cnt = 0; 90 scanf("%s%s", str1, str2); 91 for(int i = 1; i <= 3; i++) 92 { 93 for(int j = 1; j <= 3; j++) 94 { 95 ch = str1[(i-1)*3+j-1]; 96 if(ch == ‘X‘) 97 { 98 a[i][j] = 0; 99 sx = i; 100 sy = j; 101 }else 102 a[i][j] = ch - ‘0‘; 103 b[cnt++] = a[i][j]; 104 } 105 } 106 target = 0; 107 getchar(); 108 for(int i = 1; i <= 9; i++){ 109 target *= 10; 110 ch = str2[i-1]; 111 if(ch == ‘X‘) 112 target += 0; 113 else{ 114 target += ch-‘0‘; 115 postion[ch-‘0‘] = i; 116 } 117 } 118 while(!ok) 119 { 120 vis.clear(); 121 IDAstar(sx, sy, INF, 0); 122 deep++;//一层一层增加搜索的深度 123 } 124 } 125 126 return 0; 127 }
标签:should esc print href astar enter alt 返回 stream
原文地址:http://www.cnblogs.com/Penn000/p/7580610.html