spiral grid
时间限制:
2000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
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<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#include<cmath>
#define N 100
using namespace std;
int map[N][N];
bool vis[N][N];
int ex,ey,bx,by;
int maze[N][N];
void init(int *t,int n,int x,int y)
{
if(n==0)return;
int t1,t2,t3,t4;
t1=t2=t3=t4=n-1;//循环n-1遍,打印n-1个数
while(t1--)map[x][y++]=(*t)--;//右
while(t2--)map[x++][y]=(*t)--;//下
while(t3--)map[x][y--]=(*t)--;//左
while(t4--)map[x--][y]=(*t)--;//上
init(t,n-2,x+1,y+1);
}
int prime[10015];
struct node
{
int x,y,step;
node(int a,int b,int c):x(a),y(b),step(c){
}
node(){
}
};
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
int bfs()
{
queue<node>q;
q.push(node(bx,by,0));
vis[bx][by]=true;
while(!q.empty())
{
node cur=q.front();
if(cur.x==ex&&cur.y==ey)return cur.step;
q.pop();
for(int i=0;i<4;i++)
{
int xx=cur.x+dir[i][0];
int yy=cur.y+dir[i][1];
if(xx<0||xx>=N||yy<0||yy>=N||vis[xx][yy]||!prime[map[xx][yy]])continue;
vis[xx][yy]=true;
q.push(node(xx,yy,cur.step+1));
}
}
return -1;
}
int main()
{
int t=N*N;
init(&t,N,0,0);
int x,y;
int cnt=0;
memset(prime,0,sizeof(prime));
prime[0]=prime[1]=1;
for(int i=2;i<=10000;i++)
{
if(prime[i])continue;
for(int j=2*i;j<=10000;j+=i)
{
prime[j]=1;
}
}
while(~scanf("%d%d",&x,&y))
{
printf("Case %d: ",++cnt);
if(prime[y]==0)
{
printf("impossible\n");
continue;
}
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
vis[i][j]=false;
if(map[i][j]==x)
{
bx=i;by=j;
}
if(map[i][j]==y)
{
ex=i;ey=j;
}
}
}
if(bx==ex&&by==ey)
{
printf("impossible\n");
continue;
}
int res=bfs();
if(res==-1)
{
printf("impossible\n");
continue;
}
else printf("%d\n",res);
}
return 0;
}
终点不能是素数啊啊啊啊啊,运行了好一会,素数在开始的时候用筛法打表,主要是那个地图,学知识了,这两部弄完之后bfs,这一题挺不错的。