bfs(与路径相关)

/*********
Author Smile
https://vjudge.csgrandeur.cn/contest/477341#problem/H
学到了
1. bfs 又是最短路径的查找,而且还是动态连续的
2. bfs 中必须对符合条件的进行bfs, 如果有不符合条件的 push 进来,很可能会出错,路径的最短或许会变更短
3. bfs 还是一样的模板,最重要的还是分析过程
*********/ 
#include <iostream>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
const int N = 1e4 + 10;
int T;
int money[N];
int vis[N];
int t[4];

void fenjie(int x)
{
	t[0] = x / 1000;
	t[1] = x % 1000 / 100;
	t[2] = x % 100 / 10;
	t[3] = x % 10;
}

int number(int a, int b, int c, int d)
{
	return a * 1000 + b * 100 + c * 10 + d;
}

int prime(int x)
{
	int temp = sqrt(x);
	if (x < 1000 || x > 10000)
		return 0;
	for (int i = 2; i <= sqrt(x); ++i)
	{
		if (x % i == 0)
			return 0;
	}
	return 1;
}

int bfs(int x, int y)
{
	queue<int> q;
	q.push(x);
	vis[x] = 1;
	if (x == y)
		return 0;
	while (!q.empty())
	{
		int v = q.front();
		q.pop();
		
		fenjie(v);
		// cout << v << ' ' << y << endl;
		// cout << t[0] << ' ' << t[1] << ' ' << t[2] << ' ' << t[3] << endl;
		for (int i = 0; i <= 3; ++i)
		{
			int temp = t[i];
			for (int j = 0; j <= 9; ++j)
			{
				if (j == temp)
					continue;
				t[i] = j;
				int vtemp = number(t[0], t[1], t[2], t[3]);
				if (!vis[vtemp] && prime(vtemp))
				{
					vis[vtemp] = 1;
					money[vtemp] = money[v] + 1;// bfs 动态记录路径 
					q.push(vtemp);
				}
				if (vtemp == y)
					return money[vtemp];
			}
			t[i] = temp;
		}
		if (v == y)
			return money[v];
	}
	return -1;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> T;
	while (T--)
	{
		int a, b;
		cin >> a >> b;
		memset(vis, 0, sizeof vis);
		memset(money, 0, sizeof money);
		int pos = bfs(a, b);
		if (pos == -1)
			cout << "Impossible" << endl;
		else 
			cout << pos << endl;	
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值