/** * Title : A Famous Grid * url: http://acm.hdu.edu.cn/showproblem.php?pid=4255 * Time: 2012-7-26- 19:00 around * stratege: BFS, Prime Number * Author: Johnsondu * Status: 6340382 2012-07-26 19:23:33 Accepted 4255 1718MS 6260K 2349 B */ #include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <queue> using namespace std ; const int MAXN = 1000005 ; int mat[1005][1005] ; bool mark[1005][1005], flag, prime[MAXN] ; int sVal, dVal ; int sx, sy, ans ; int dx[4] = {0, 0, 1, -1} ; int dy[4] = {1, -1, 0, 0} ; struct Node { int x, y ; int step ; }; Node cur, next ; void Graph () //蛇形填数 制图 { int x, y, z, b, i, c = 1000000 ; x = 1; y = 1000; z = 1; b = 1000 ; while (c > 0) { for (i = x; i <= y; i ++) mat[x][i] = c -- ; x ++ ; for (i = x; i <= y; i ++) mat[i][y] = c -- ; y -- ; for (i = y; i >= z; i --) mat[b][i] = c -- ; b -- ; for (i = b; i > z; i --) mat[i][z] = c -- ; z ++ ; } } void IsNotPrime () // 筛选1000000内的素数 { int i, tmp ; memset (prime, true, sizeof (prime)) ; prime[0] = prime[1] = false ; for (i = 4; i < MAXN; i += 2) prime[i] = false ; for (i = 3; i < MAXN; i += 2) { if (prime[i]) { tmp = 2 * i ; while (tmp < MAXN) { prime[tmp] = false ; tmp += i ; } } } } void init () //初始化 并找出初始位置 { int i, j ; memset (mark, false, sizeof (mark)) ; flag = false ; ans = 0 ; for (i = 1; i < 1001; i ++) for (j = 1; j < 1001; j ++) { if (mat[i][j] == sVal) { sx = i ; sy = j ; return ; } } } bool safe (int x, int y) //判断是否可行: 越界,标记与否,素数 { if (x < 1001 && y < 1001 && x > 0 && y > 0 && !mark[x][y] && !prime[mat[x][y]]) return true ; return false ; } void bfs () //常规的bfs部分 { int i ; cur.x = sx ; cur.y = sy ; cur.step = 0 ; mark[sx][sy] = true ; queue <Node> Q ; Q.push (cur) ; while (!Q.empty ()) { cur = Q.front () ; Q.pop () ; for (i = 0; i < 4; i ++) { next.x = cur.x + dx[i] ; next.y = cur.y + dy[i] ; if (safe (next.x, next.y)) { next.step = cur.step + 1; if (mat[next.x][next.y] == dVal) { ans = next.step ; flag = true ; return ; } mark[next.x][next.y] = true ; Q.push (next) ; } } } } int main () { int cas = 1; Graph () ; IsNotPrime () ; while (scanf ("%d%d", &sVal, &dVal) != EOF) { init () ; bfs () ; printf ("Case %d: ", cas ++) ; if (flag) printf ("%d\n", ans) ; else printf ("impossible\n") ; } return 0 ; }