Prime Path POJ - 3126

9 篇文章 0 订阅

//判断条件写错了,导致没结果,然后就是最高位不能为0,否则会导致结果出错.... Both numbers are four-digit primes (without leading zeros)......

/*思路:因为要找最少变换素数次数,
所以,用bfs解,每次每位由0-9选择,
存入队列,直到符合最终结果,
此时步数为最短步数*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>

using namespace std;

const int N = 10000;

bool prime[N];

struct node{
	int a;
	int step;
	
	node(){
		a = 0;
		step = 0;
	}
	node(int ta, int tb){
		a = ta;
		step = tb;
	}
};

queue<node> q;

void SetPrime()//素数判定 
{
	memset(prime, true, sizeof(prime));
	
	for(int i=2; i<sqrt(N); i++){
		for(int j=i*i; j<N; j += i){
			prime[j] = false;
		}
	}	
} 

void BFS(int s, int e)
{
	bool vis[N];
	
	memset(vis, false, sizeof(vis));
	
	vis[s] = true;
	while(!q.empty()){
	
	node tmp = q.front();
	q.pop();
		
	if(tmp.a == e){//结束条件 
		cout << tmp.step << endl;
		return;
	}
	
	for(int i=0; i<4; i++){//位数:个十百千 
		for(int j=0; j<10; j++){//要变为的数 
			node tmp2;
			if(i == 3 && j == 0)
				j++;
			int CO = pow(10, i+1);//进位 
			int mod = pow(10, i);//模数 
	//		cout << CO << " "<< mod << endl; 
			tmp2.a = tmp.a/CO*CO+j*mod+(tmp.a)%mod;
		//	cout << tmp.a/pow(10, i+1)*pow(10, i+1) << " "<< j*pow(10, i) << " " <<(tmp.a)%mod << endl;
	//			cout << tmp.a << " "<< tmp2.a << endl;
			if(prime[tmp2.a] && !vis[tmp2.a]){//是素数并且未被拜访过 
	//			cout << tmp.a << endl;
	//			cout << tmp2.a << endl; 
				vis[tmp2.a] = true;//标记已被拜访过 
				tmp2.step = tmp.step+1;//步数加一 
				q.push(tmp2);
			}
		}
	}
	}
}

int main()
{
	SetPrime();
		
	int n, st, ed;
	
	cin >> n;
	
	while(n--){
		//以防万一,先清空吧 
		while(!q.empty()){
			q.pop();
		}
		
		cin >> st >> ed;
	
		node tmp(st, 0);
		q.push(tmp);
	
		BFS(st, ed);
	}
	
	return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值