您的位置:首页 > 其它

poj 3126 Prime Path 【bfs】

2015-08-03 16:19 381 查看
题目地址:http://poj.org/problem?id=3126

Input

One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).
Output

One line for each case, either with a number stating the minimal cost or containing the word Impossible.
Sample Input

3
1033 8179
1373 8017
1033 1033

Sample Output

6
7
0
分析:从一个四位素数a 变到另一个四位素数b,求最少的变换次数。bfs求最少的次数!(变换的要求请读题目)
一开始在记录一个数是否被访问过的时候,用了一种比较的方式,即:比较当前要生成的数和cur是否相同,这种
判断是否该数字是否访问过的方法是不对的,因为这样判断还是会导致一个数可能会被多次加入队列,最后TLE。
故,改为vis[]标记判断是否访问过,这样每个数顶多会被加入队列一次。AC!
代码:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <cmath>
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
#define N 100000+100

using namespace std;

struct node
{
int a, b, c, d; //a不能等于0
int path;
};

int f[10010];
bool vis[10010];

void sushu()
{
int i, dd=sqrt(10000+0.5);
memset(f, 0, sizeof(f));
i=2; f[1]=f[0]=1; //not
while(i<=dd){
for(int j=i+i; j<=10000; j+=i)
f[j]=1; // not
i++;
while(f[i]==1) i++;
}
}

int main()
{
sushu(); //筛素数
// printf("%d  %d", f[1001], f[1003] );

int tg; scanf("%d", &tg);
int dd, ff;
int i, j;

while(tg--){
scanf("%d %d", &dd, &ff);
if(dd==ff){
printf("0\n"); continue;
}
node s, e;
s.a=dd/1000; s.b=dd/100%10; s.c=dd/10%10; s.d=dd%10; s.path=0;
e.a=ff/1000; e.b=ff/100%10; e.c=ff/10%10; e.d=ff%10;

queue<node>q; bool flag=false;
q.push(s); node cur;
int ans=0;
memset(vis, false, sizeof(vis));
vis[dd]=true;

while(!q.empty()){
cur=q.front(); q.pop();

for(i=1; i<=9; i+=2){//枚举个位 偶数排除
int temp=cur.a*1000+cur.b*100+cur.c*10+i;
if(!vis[temp] && f[temp]==0){
node cc=cur; cc.d=i; cc.path=cur.path+1;
vis[temp]=true;
if(temp==ff){
flag=true; ans=cc.path; break;
}
q.push(cc);
}
}
if(flag) break;

for(i=0; i<=9; i++){ //枚举个位

int temp=cur.a*1000+cur.b*100+i*10+cur.d;
if(!vis[temp] &&f[temp]==0){
node cc=cur; cc.c=i; cc.path=cur.path+1;
vis[temp]=true;
if(temp==ff){
flag=true; ans=cc.path; break;
}
q.push(cc);
}
}
if(flag) break;

for(i=0; i<=9; i++){//枚举百位
int temp=cur.a*1000+i*100+cur.c*10+cur.d;
if(!vis[temp] &&f[temp]==0){
node cc=cur; cc.b=i; cc.path=cur.path+1;
vis[temp]=true;
if(temp==ff){
flag=true; ans=cc.path; break;
}
q.push(cc);
}
}
if(flag) break;

for(i=1; i<=9; i++){ //枚举千位 千位不能为0
int temp=i*1000+cur.b*100+cur.c*10+cur.d;
if(!vis[temp] &&f[temp]==0){
node cc=cur; cc.a=i; cc.path=cur.path+1;
vis[temp]=true;
if(temp==ff){
flag=true; ans=cc.path; break;
}
q.push(cc);
}
}
if(flag) break;
}
if(flag) printf("%d\n", ans );
else printf("Impossible\n");
}
return 0;
}


View Code


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: