poj 3126 Prime Path([kuangbin带你飞]专题一 简单搜索)

题目连接:题目

题目大意:两个素数,每次可以改变前一个数的某一位,并且改变完还是素数,求从第一个数变成第二个数的最小步数

解题思路:能读懂题目就差不多能知道用bfs,枚举每一位,改变数,看是不是素数,

#include<cstdio>
#include<queue>
#include<algorithm>
#include<map>
#include<utility>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;
bool prime[10000+10];
void get_prime(){
	memset(prime,true,sizeof(prime));
	prime[1]=false;
	for(int i=2;i*i<=10000;i++){
		if(prime[i]){
			for(int j=i*i;j<=10000;j+=i) prime[j]=false;
		}
	}
}
int cnonvert(string str){
	return (str[0]-'0')*1000+(str[1]-'0')*100+(str[2]-'0')*10+(str[3]-'0');
}

typedef pair<string,int> p;
string l,r;

void bfs(){
	map<string,int> book;
	queue<p> q;
	book[l]=1;
	q.push(p(l,0));

	while(!q.empty()){
		p temp=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			string str = temp.first;
			for(int j=0;j<=9;j++){
				if(!i&&!j) continue;
				str[i]='0'+j;
				if(str==r){
					printf("%d\n",temp.second+1);
					return ;
				}
			//	cout<<str<<endl; 
				if(prime[cnonvert(str)]){
				//	cout<<str<<endl; 
					if(!book[str]){
						book[str]=1;
						p tt;
						tt.first=str,tt.second=temp.second+1;
						q.push(tt);
					}
				}
			}
		}
	}
	printf("Impossible\n");

}






int main(int argc, char const *argv[])
{
	int t;
	scanf("%d",&t);
	get_prime();
	while(t--){
		cin>>l>>r;
		if(l==r) printf("0\n");
		else bfs();
	}
	return 0;
}


posted @ 2016-10-16 15:47  hong-ll  阅读(127)  评论(0编辑  收藏  举报