【F - Prime Path】

思路:

  • wow
  • 第一次独立解出一道略微变形的搜索题。
  • dfs:素数筛预处理,对每个数位搜索就可以了。
  • 注意:用 pow() 一定要用 (int) 进行类型转换,无论是除法还是取余。因为 pow() 返回值是 double 类型。

代码:

  • 63ms 720kB
//63ms		720kB


#include <iostream>
#include <cstring>
#include <queue>
#include <cmath>

using namespace std;

const int maxn = 10005 ;
const int submaxn = 100;

bool unprime[maxn];
bool vis[maxn];
int L , R;
int ans;
struct node{
	int n;
	int step;
	friend bool operator > (const node & a , const node & b){
		return a.step > b.step;
	}
	node(int n , int step) : n(n) , step(step) {} ;
};
priority_queue<node , vector<node> , greater<node> > Q;

void isprime(){
	memset(unprime,false,sizeof(unprime));
	unprime[0] = unprime[1] = true;
	for(int i=2;i<=submaxn;i++){
		if(!unprime[i]){
			for(int j=i*i ; j<maxn ; j+=i)
				unprime[j] = true;
		}
	}
	return ;
}

void init(){
	ans = 0;
	memset(vis , false , sizeof(vis));
	while(!Q.empty())
		Q.pop();
	return ;
}

void qpush(int n , int s){
	for(int i=0;i<4;i++){
		int left;
		int temp;
		if(!i){
			left = n%1000;
			for(int j=1;j<=9;j++){	
				temp = left + j*1000;
			//	if(temp == n)
			//		continue;
				if(vis[temp])
					continue;
				if(!unprime[temp]){
					if(temp == R){
						ans = s+1;
						return ;
					}
					Q.push(node(temp , s+1));
					vis[temp] = true;
				}
			}
		}
		else{
			left = n / (int)pow(10,4-i) * pow(10,4-i) + n % (int)pow(10 , 3-i) ;
			for(int j=0;j<=9;j++){
				temp = left + j * pow(10 , 3-i);
			//	if(temp == n)
			//		continue;
				if(vis[temp])
					continue;
				if(!unprime[temp]){
					if(temp == R){
						ans = s+1;
						return ;
					}
					Q.push(node(temp , s+1));
					vis[temp] = true;
				}
			}
		}
	}
	return ;
}

void bfs(){
	if(L == R)
		return ;
	Q.push(node(L , 0));
	vis[L] = true;
	while(!Q.empty()){
		node t = Q.top();Q.pop();
		qpush(t.n , t.step);
		if(ans)
			return ;
	}
	return ;
}

int main(){
	isprime();
	int T;cin>>T;
	while(T--){
		init();
		cin>>L>>R;
		bfs();
		if(ans || L == R)
			cout<<ans<<endl;
		else
			cout<<"Impossible"<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值