poj3216

prime path

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<math.h>
#include<set>
using namespace std;
typedef long long ll;
int book[10010];
struct node
{
	int x, step;
}s, t;
bool prime(int n)
{
	for (int i = 2; i * i <= n; i++)
	{
		if (n % i == 0)
		{
			return false;
		}
	}
	return true;
}
void bfs(int a, int b)
{
	queue<node>q;
	s.x = a;
	s.step = 0;
	book[s.x] = 1;
	q.push(s);
	while (!q.empty())
	{
		s = q.front();
		for (int i = 1; i <= 9; i = i + 2)//枚举个位的数字,个位不可能是偶数
		{
			int c = s.x / 10 * 10 + i;
			if (c == b)
			{
				printf("%d\n", s.step + 1);
				return;
			}
			if (!book[c] && prime(c))
			{
				book[c] = 1;
				t.x = c;
				t.step = s.step + 1;
				q.push(t);
			}
		}
		for (int i = 0; i <= 9; i++)//十位
		{
			int c = s.x / 100 * 100 + i * 10 + (s.x % 10);
			if (c == b)
			{
				printf("%d\n", s.step + 1);
				return;
			}
			if (!book[c] && prime(c))
			{
				book[c] = 1;
				t.x = c;
				t.step = s.step + 1;
				q.push(t);
			}
		}
		for (int i = 0; i <= 9; i++)//百位
		{
			int c = s.x / 1000 * 1000 + i * 100 + (s.x % 100);
			if (c == b)
			{
				printf("%d\n", s.step + 1);
				return;
			}
			if (!book[c] && prime(c))
			{
				book[c] = 1;
				t.x = c;
				t.step = s.step + 1;
				q.push(t);
			}
		}
		for (int i = 1; i <= 9; i++)//千位
		{
			int c = i * 1000 + (s.x % 1000);
			if (c == b)
			{
				printf("%d\n", s.step + 1);
				return;
			}
			if (!book[c] && prime(c))
			{
				book[c] = 1;
				t.x = c;
				t.step = s.step + 1;
				q.push(t);
			}
		}
		q.pop();
	}
	printf("Impossible\n");
	return;
}
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int a, b;
		memset(book, 0, sizeof(book));
		cin >> a >> b;
		if (a == b)
		{
			printf("0\n");
		}
		else
		{
			bfs(a, b);
		}
	}
	return 0;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值