#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
int map[1009][1009],mark[1009][1009];
int a[1000001],xx,yy;
int dist[4][2]= {0,1,0,-1,1,0,-1,0};
struct node
{
int x,y,step;
};
void grap()
{
int c=1000000,x,y,z,b,i;
x=1;
y=1000;
z=1;
b=1000;
while(c>0)
{
for(i=x; i<=y; i++)
map[x][i]=c--;
x++;
for(i=x; i<=y; i++)
map[i][y]=c--;
y--;
for(i=y; i>=z; i--)
map[b][i]=c--;
b--;
for(i=b; i>z; i--)
map[i][z]=c--;
z++;
}
}
void prim()
{
int i,j;
memset(a,0,sizeof(a));
a[1]=1;
for(i=2; i<=1000; i++)
if(a[i]==0)
for(j=2; i*j<=1000000; j++)
a[i*j]=1;
}
int bfs(int aa,int bb)
{
queue<node>q;
node cur,next;
cur.x=aa;
cur.y=bb;
cur.step=0;
mark[aa][bb]=1;
if(map[cur.x][cur.y]==yy)return cur.step;
q.push(cur);
while(!q.empty())
{
cur=q.front();
q.pop();
for(int i=0; i<4; i++)
{
next.x=cur.x+dist[i][0];
next.y=cur.y+dist[i][1];
if(next.x>=1&&next.y>=1&&next.x<=1000&&next.y<=1000&&mark[next.x][next.y]==0&&a[map[next.x][next.y]]==1)
{
next.step=cur.step+1;
if(map[next.x][next.y]==yy&&a[map[next.x][next.y]]==1)return next.step;
mark[next.x][next.y]=1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int i,j,a,b,z=1;
prim();
grap();
while(scanf("%d%d",&xx,&yy)!=-1)
{
for(i=1; i<=1000; i++)
{
for(j=1; j<=1000; j++)
if(map[i][j]==xx)
{
a=i;
b=j;
break;
}
if(j<=1000)
break;
}
memset(mark,0,sizeof(mark));
int ans=bfs(a,b);
if(ans==-1)
printf("Case %d: impossible\n",z++);
else
printf("Case %d: %d\n",z++,ans);
}
return 0;
}
Hdu--4255 螺旋矩阵
最新推荐文章于 2019-10-13 13:19:45 发布