F - Find The Multiple(字符串解法)

19 篇文章 0 订阅
15 篇文章 0 订阅

题目:F - Find The Multiple

题意分析:给一个质数A和一个质数B每次变换可以改变A的各十百千位,问至少经过多少变换才能将A变为B
思路:
利用字符串储存AB,BFS字符串A的每一位的各种情况

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

#define x first
#define y second
#define PII pair<int, string>

using namespace std;

const int N = 20000;

int st[N];

int Atoi(string s)
{
	int sum = 0;
	for(int i = 0; s[i] != '\0'; i ++)
		sum = sum * 10 + s[i] - '0';
	
	return sum;
}
bool isprime(int x)
{
    if(x < 2) return false;
    for(int i = 2; i <= x / i; i ++)
    {
        if(x % i == 0) return false;
    }
    return true;
}

int bfs(string a, string b)
{
    memset(st, 0, sizeof st);
    queue<PII> Q;
	st[Atoi(a)] = 1;
    Q.push({0, a});
    while(!Q.empty())
    {
        PII now = Q.front();
        if(now.y == b) return now.x;
        Q.pop();
        
        for(int i = 0; i < 4; i ++)
        {
            for(int j = 0; j <= 9; j ++)
            {
                PII p = now;
                if(i == 0 && j == 0) continue;
                if(j + '0' == p.y[i]) continue;
                
                p.y[i] = j + '0';
                if(!isprime(Atoi(p.y))) continue;
                if(st[Atoi(p.y)]) continue;
                
				// cout << p.y << endl;
                p.x = now.x + 1;
                st[Atoi(p.y)] = 1;
                if(p.y == b) return p.x; // 不写会TLE...
                Q.push(p);
            }
        }
        
    }
    return -1;
}
int main()
{
    int t;
    cin >> t;
    while(t --)
    {
        string a, b;
        cin >> a >> b;
        if(bfs(a, b) == -1) cout << "Impossible" << endl;
        else
            cout << bfs(a, b) << endl;
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值