KuangBin 专题一:简单搜索 Prime Path

题目链接:
传送门

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;

struct node {
	int num,step;
};
const int N = 10005;
bool isprime[N],used[N];
int prime[N],change[4], cnt,s,e;

//欧拉筛筛选素数
void oulashai() {
	for (int i = 2; i <= N; i++) {
		if (!isprime[i]) prime[cnt++] = i;
		for (int j = 0; j < cnt; j++) {
			if (i * prime[j] > N) break;
			isprime[i * prime[j]] = true;
			if (i % prime[j] == 0) break;
		}
	}
}

int bfs(int sta) {
	if(sta==e)return 0;
	queue<node> q;
	node start= {sta,0};
	q.push(start);
	used[sta]=1;
	int f=0;
	while(!q.empty()) {
		node cur=q.front();
		q.pop();
		//替换个位数
		for(int i=1; i<=9; i=i+2) {
			int theNum=cur.num/10*10+i;
			if(theNum==e) {
				f=cur.step+1;
				return f;
			}
			if(used[theNum]==0&&isprime[theNum]==0) {
				used[theNum]=1;
				node tmp= {theNum,cur.step+1};
				q.push(tmp);
			}
		}
		//替换十位数
		for(int i=0; i<=9; i++) {
			int theNum=cur.num/100*100+i*10+cur.num%10;
			if(theNum==e) {
				f=cur.step+1;
				return f;
			}
			if(used[theNum]==0&&isprime[theNum]==0) {
				used[theNum]=1;
				node tmp= {theNum,cur.step+1};
				q.push(tmp);
			}
		}
		//替换百位数
		for(int i=0; i<=9; i++) {
			int theNum=cur.num/1000*1000+i*100+cur.num%100;
			if(theNum==e) {
				f=cur.step+1;
				return f;
			}
			if(used[theNum]==0&&isprime[theNum]==0) {
				used[theNum]=1;
				node tmp= {theNum,cur.step+1};
				q.push(tmp);
			}
		}
		//替换千位数
		for(int i=1; i<=9; i++) {
			int theNum=cur.num%1000+i*1000;
			if(theNum==e) {
				f=cur.step+1;
				return f;
			}
			if(used[theNum]==0&&isprime[theNum]==0) {
				used[theNum]=1;
				node tmp= {theNum,cur.step+1};
				q.push(tmp);
			}
		}
	}
	//如果在搜完所有情况后依然没有所要的结果返回-1
	return -1;
}

int main() {
	oulashai();
	int t;
	cin>>t;
	while(t--) {
		memset(used,0,sizeof(used));
		cin>>s>>e;
		int ans=bfs(s);
		cout<<ans<<endl;
	}
	return 0;
}

这道题的大致思路是首先,先把当前数存入队列中,然后分别对该数的个位,十位,百位,千位进行处理。每次处理后看当前数字是否为质数,是则存入队列中,并标记该数字为已搜索。如果哪次处理后得到了所需的数字则return步骤数,如果最终没有处理出这个数则返回-1。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值