poj-3126

题意:给两个素数a,b,求将a变成b的最小次数,一次只能变一位而且每次变化后的数字必须是素数。

题解:bfs

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <string>
#include <map>
#include <cstring>
#include <math.h>
#include <stdlib.h>
#include <time.h>

#define ll long long
#define INF 0x3f3f3f3f

using namespace std;

bool vis[10000];
int n,m;

struct node{
	int x;
	int step;
};

int judge(int x){
	if(x==1)return 0;
	for(int i = 2 ; i <= sqrt(x) ; i++){
		if(x%i==0){
			return 0;
		}
	}
	return 1;
}

void bfs(){
	memset(vis,0,sizeof vis);
	queue<node>q;
	node a;
	a.step = 0;
	a.x = n;
	vis[a.x] = true;
	q.push(a);
	while(!q.empty()){
		node now = q.front();
		q.pop();
		if(now.x==m){
			cout<<now.step<<endl;
			return;
		}
		for(int j = 1 ; j <= 4 ; j++){
			if(j==1){
				for(int i = 1 ; i <= 9 ; i+=2){
					node next = now;
					next.x = next.x/10*10+i;
					if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
						vis[next.x] = true;
						next.step++;
						q.push(next);
					}
				}
			}else if(j==2){
				for(int i = 0 ; i <= 9 ; i++){
					node next = now;
					next.x = next.x/100*100+i*10+now.x%10;
					if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
						vis[next.x] = true;
						next.step++;
						q.push(next);
					}
				}
			}else if(j==3){
				for(int i = 0 ; i <= 9 ; i++){
					node next = now;
					next.x = next.x/1000*1000+i*100+now.x%100;
					if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
						vis[next.x] = true;
						next.step++;
						q.push(next);
					}
				}
			}else{
				for(int i = 1 ; i <= 9 ; i++){
					node next = now;
					next.x = i*1000+now.x%1000;
					if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
						vis[next.x] = true;
						next.step++;
						q.push(next);
					}
				}
			}
		}
	}
	cout<<"Impossible"<<endl;
}

int main(){
	int t;
	cin>>t;
	while(t--){
		scanf("%d %d",&n,&m);
		bfs();
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值