| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 12060 | Accepted: 6843 |
Description
The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices. 1033The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.
1733
3733
3739
3779
8779
8179
Input
Output
Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0传送门
题意:有一个素数主义者要换四位数的门牌,给出旧门牌号和新门牌号,每次变换只能换一位数,而且他不与许看到不是素数的四位数出现,求最少经过多少次变换可以让旧门牌号换成新门牌号。
思路:BFS,每次变换只能换一位数,所以要对每一位数字分别处理,而且要记得标记,入队的书就标记上,不要再次入队。只有素数才入队,所以每次入队前判断是不是素数消耗太大,直接打一个素数表,1~10000即可,筛法保持标记形式的状态,不是素数就标记成0即可。
//612 KB 0 ms
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int _,flag;
int a,b;
int prime[10010];
bool book[10010];
queue<pair<int,int> >que;
void ini()
{
flag=0;
memset(book,0,sizeof(book));
scanf("%d%d",&a,&b);
while(!que.empty()) que.pop();
}
void bfs()
{
que.push(make_pair(a,0) );
book[a]=1;
while(!que.empty()){
pair<int,int> t=que.front();
que.pop();
if(t.first==b) {printf("%d\n",t.second);flag=1;return ;}
int x=t.first;
for(int i=1;i<=9;i++){
int nx=x%1000+i*1000;//只变换千位数
if(prime[nx]&&!book[nx]) {que.push(make_pair(nx,t.second+1)); book[nx]=1;}
}
for(int i=0;i<=9;i++){
int nx=x%100+1000*(x/1000)+i*100; //只变换百位数
if(prime[nx]&&!book[nx]) {que.push(make_pair(nx,t.second+1)); book[nx]=1;}
}
for(int i=0;i<=9;i++){
int nx=x%10+100*(x/100)+i*10; //只变换十位数
if(prime[nx]&&!book[nx]) {que.push(make_pair(nx,t.second+1)); book[nx]=1;}
}
for(int i=0;i<=9;i++){
int nx=10*(x/10)+i;//只变换个位数
if(prime[nx]&&!book[nx]) {que.push(make_pair(nx,t.second+1)); book[nx]=1;}
}
}
}
int main()
{
memset(prime,-1,sizeof(prime));
/*素数筛*/
for(int i=2;i<=10;i++) //剔除10以内的全部非素数
for(int j=2;j*j<=i;j++)
if(i%j==0) prime[i]=0;
prime[1]=0;
for(int i=1;i<=10;i++) //剔除100以内的全部非素数,顺便剔除掉100~10000之间的一些非素数
if(prime[i])
for(int j=2;i*j<=10000;j++)
prime[i*j]=0;
for(int i=11;i<=100;i++) //剔除100~10000之间的全部非素数
if(prime[i])
for(int j=2;i*j<=10000;j++)
prime[i*j]=0;
scanf("%d",&_);
while(_--)
{
ini();
bfs();
if(!flag) printf("Impossible\n");
}
return 0;
}
原文:http://blog.csdn.net/kalilili/article/details/42979379