描述Xiaod has recently discovered the grid named "spiral grid".
Construct the grid like the following figure. (The grid is actually infinite. The figure is only a small part of it.)
Considering traveling in it, you are free to any cell containing a composite number or 1, but traveling to any cell containing a prime number is disallowed. In addition, traveling from a prime number is disallowed, either. You can travel up, down, left or right, but not diagonally. Write a program to find the length of the shortest path between pairs of nonprime numbers, or report it's impossible.
-
输入
-
Each test case is described by a line of input containing two nonprime integer 1 <=x, y<=10,000.
-
输出
-
For each test case, display its case number followed by the length of the shortest path or "impossible" (without quotes) in one line.
-
样例输入
-
1 4
9 32
10 12
-
样例输出
Case 1: 1
Case 2: 7
Case 3: impossible
//起点可以是素数,终点不可以是素数
#include
#include
#include
#include
using namespace std;
int map[105][105];
int vis[105][105];
int prime[10005];
int dir[4][2]={1,0,0,1,-1,0,0,-1};
struct point
{
int x,y,step;
};
void build()
{
int i,j,k,num;
num = 10000;
k = 1;
while(num>0)
{
for(j=k;j<=100-k;j++)
{
map[k][j]=num;
num --;
}
for(i=k;i<=100-k;i++)
{
map[i][101-k] = num;
num --;
}
for(j=101-k;j>k;j--)
{
map[101-k][j] = num;
num --;
}
for(i=101-k;i>k;i--)
{
map[i][k] = num;
num --;
}
k++;
}
}
int is_prime()
{
int i,j;
prime[0]=0; // 0本来不是素数,在这里用于边界
prime[1]=1;
for(i=2;i<=10000;i++)
{
if(!prime[i])
for(j=2*i;j<=10000;j=j+i)
prime[j]=1;
}
}
int bfs(int a,int b,int num)
{
point now,next;
queueq;
int i,j,k;
now.x = a;
now.y = b;
now.step = 0;
q.push(now);
vis[a][b]=1;
while(!q.empty())
{
now = q.front();
q.pop();
for(i=0;i<4;i++)
{
next.x = now.x+dir[i][0];
next.y = now.y+dir[i][1];
next.step = now.step+1;
if(map[next.x][next.y]==num)
return next.step;
if((!vis[next.x][next.y])&&prime[map[next.x][next.y]])
{
q.push(next);
vis[next.x][next.y]=1;
}
}
}
return 0;
}
int main()
{
int i,j,t,s,e,test,a,b;
is_prime();
build();
test = 0;
while(scanf("%d%d",&s,&e)==2)
{
memset(vis,0,sizeof(vis));
test ++;
if(!prime[e])
{
printf("Case %d: impossible\n",test);
continue;
}
for(i=1;i<=100;i++)
for(j=1;j<=100;j++)
{
if(map[i][j]==s)
{
a=i;
b=j;
break;
}
}
t = bfs(a,b,e);
if(t == 0)
printf("Case %d: impossible\n",test);
else
printf("Case %d: %d\n",test,t);
}
return 0;
}