POJ 3126 Prime Path bfs

来源:http://poj.org/problem?id=3126

题意:给你两个四位数的素数,求最少经过多少步的变化能够从一个素数变到另一个素数。在变得过程中,要求都是素数,而且每个新的数和原来的数只有一位不一样。

思路:bfs,对每一位判断即可。

代码:

#include <iostream>
#include <cstdio>
#include <string.h>
#include <cmath>
#include <queue>
using namespace std;

#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int N = 10010;
int flag[N],isqueue[N];
int step[N];
int q,b,g,s;
void init(){
	CLR(flag,0);
	for(int i = 2; i <= sqrt(N+0.5); ++i){
		if(!flag[i]){
		   for(int j = i * 2; j < N; j += i)
			   flag[j] = 1;
		}
	}
}
void fun(int x){
	q = x / 1000;
	b = x % 1000 / 100;
	s = x % 100 / 10;
	g = x % 10;
}
int fun2(int x,int y,int z,int w){
	return x * 1000 + y * 100 + z * 10 + w;
}
void bfs(int p1,int p2){
	queue<int> qq;
	qq.push(p1);
	isqueue[p1] = 1;
	step[p1] = 0;
	while(1){
		int x = qq.front();
		qq.pop();
		if(x == p2){
			break;
		}
		fun(x);
		for(int i = 1; i <= 9 ; ++i){
		   int y = fun2(i,b,s,g);
		   if(!flag[y] && !isqueue[y]){
			   qq.push(y);
			   isqueue[y] = 1;
			   step[y] = step[x] + 1;
		   }
		}
		for(int i = 0;i <= 9; ++i){
		   int y = fun2(q,i,s,g);
		   if(!flag[y] && !isqueue[y]){
			   qq.push(y);
			   isqueue[y] = 1;
			   step[y] = step[x] + 1;
		   }
		}
		for(int i = 0; i <= 9; ++i){
		   int y = fun2(q,b,i,g);
		   if(!flag[y] && !isqueue[y]){
			   qq.push(y);
			   isqueue[y] = 1;
			   step[y] = step[x] + 1;
		   }
		}
		for(int i = 0; i <= 9; ++i){
		   int y = fun2(q,b,s,i);
		   if(!flag[y] && !isqueue[y]){
		     qq.push(y);
			 isqueue[y] = 1;
			 step[y] = step[x] + 1;
		   }
		}
	}
}
int main(){
	//freopen("1.txt","r",stdin);
	init();
	int numcase,p1,p2;
	scanf("%d",&numcase);
	while(numcase--){
	   scanf("%d%d",&p1,&p2);
	   if(p1 == p2){
	     printf("0\n");
		 continue;
	   }
       CLR(step,0); 
	   CLR(isqueue,0);
	   bfs(p1,p2);
	   printf("%d\n",step[p2]);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值