您的位置:首页 > 其它

poj 3126 Prime Path

2013-05-31 22:11 162 查看
Description

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int a,b;
int flag[10000];
struct node
{
int num,step;
};
bool prim[10000];
void bfs()
{
node p,temp;
int i;
p.num=a;
p.step=0;
flag[a]=0;
queue<node>q;
while(!q.empty())
{
q.pop();
}
q.push(p);
while(!q.empty())
{
p=q.front();
q.pop();
if(p.num==b)
{
printf("%d\n",p.step);
return;
}
for(i=0;i<4;i++)
{
temp=p;
temp.step=p.step+1;
if(i==0)
{
int ff=temp.num/1000;
int j;
for(j=1;j<=9;j++)
{
if(j!=ff)
{
int dd=temp.num%1000+j*1000;
if(!prim[dd] && temp.step<flag[dd])
{
temp.num=dd;
flag[dd]=temp.step;
q.push(temp);
}
}
}

}
if(i==1)
{
int ff=(temp.num/100)%10;
int j;
for(j=0;j<=9;j++)
{
if(j!=ff)
{
int dd=temp.num%100+j*100+temp.num/1000*1000;
if(!prim[dd] && temp.step<flag[dd])
{
temp.num=dd;
flag[dd]=temp.step;
q.push(temp);
}
}
}

}
if(i==2)
{
int ff=(temp.num/10)%10;
int j;
for(j=0;j<=9;j++)
{
if(j!=ff)
{
int dd=temp.num/100*100+j*10+temp.num%10;
if(!prim[dd] && temp.step<flag[dd])
{
temp.num=dd;
flag[dd]=temp.step;
q.push(temp);
}
}
}

}
if(i==3)
{
int ff=temp.num%10;
int j;
for(j=0;j<=9;j++)
{
if(j!=ff)
{
int dd=temp.num/10*10+j;
if(!prim[dd] && temp.step<flag[dd])
{
temp.num=dd;
flag[dd]=temp.step;
q.push(temp);
}
}
}
}
}
}
}
int main()
{
int t;
memset(prim,false,sizeof(prim));
prim[1]=true;
for(int i=2;i<=5000;i++)
{
for(int j=i+i;j<=10000;j+=i)
{
prim[j]=true;
}
}
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
if(a==b)
{
printf("0\n");
continue;
}
memset(flag,0x7f,sizeof(flag));
bfs();
}
return 0;
}


View Code
此题大意:

给你一个素数a ,每次只能改变一位数字,并且改成下个数也必须是素数,题目要求从a变到b最少的步数。

然后就是简单的bfs,用flag数组装每一个素数的最少步数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: