当前位置:网站首页>质数路径(DAY 99)
质数路径(DAY 99)
2022-08-02 04:22:00 【张学恒】
1:题目
给定两个四位质数 A 和 B,你需要通过最少的操作次数将 A 变为 B。
每次操作只能改变当前数的其中一位数字,并且每次操作过后,当前数必须仍然是一个质数。
例如,将 1033 变为 8179,最少需要进行 6 次操作,具体操作为:
1033 -> 1733 -> 3733 -> 3739 -> 3779 -> 8779 -> 8179
请计算并输出所需要的最少操作次数。
输入格式
第一行包含整数 T,表示共有 T 组测试数据。
每组数据占一行,包含两个四位质数 A 和 B。
输出格式
每组数据输出一行答案,表示所需最少操作次数。
如果无法做到,则输出 Impossible。
经实际测试,不存在无解情况,特此声明。
数据范围
1≤T≤100。
1000≤A,B≤9999,
保证 A 和 B 都是质数。
输入样例:
3
1033 8179
1373 8017
1033 1033
输出样例:
6
7
0
2:代码实现
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
using LL = long long;
using PII = pair<int, int>;
const int N = 2e6 + 10;
PII q[N];
bool st[N], vi[N];
void solve() {
int A, B;
cin >> A >> B;
memset(st, false, sizeof st);
memset(vi, false, sizeof vi);
auto check = [&](int x) {
for (int i = 2; i * i <= x; i ++)
if (x % i == 0) return false;
return true;
};
for (int i = 1000; i < 10000; i ++)
if (check(i)) st[i] = true;
int hh = 0, tt = -1;
q[++ tt] = {
A, 0};
while (hh <= tt) {
auto t = q[hh ++];
// cout << t.fi << endl;
if (t.fi == B) {
cout << t.se << endl;
return;
}
if (vi[t.fi]) continue;
vi[t.fi] = true;
int one, two, thr, fou;
fou = t.fi % 10, thr = (t.fi / 10) % 10;
two = (t.fi / 100) % 10, one = t.fi / 1000;
// cout << one << two << thr << fou << endl;
for (int i = 1; i <= 9; i ++) {
int x = i * 1000;
x += two * 100 + thr * 10 + fou;
if (st[x]) q[++ tt] = {
x, t.se + 1};
}
for (int i = 0; i <= 9; i ++) {
int x = one * 1000;
x += i * 100 + thr * 10 + fou;
if (st[x]) q[++ tt] = {
x, t.se + 1};
}
for (int i = 0; i <= 9; i ++) {
int x = one * 1000;
x += two * 100 + i * 10 + fou;
if (st[x]) q[++ tt] = {
x, t.se + 1};
}
for (int i = 0; i <= 9; i ++) {
int x = one * 1000;
x += two * 100 + thr * 10 + i;
if (st[x]) q[++ tt] = {
x, t.se + 1};
}
}
cout << "Impossible" << endl;
}
signed main() {
int ___ = 1;
cin >> ___;
for (; ___ -- ;) solve();
return 0;
}
边栏推荐
猜你喜欢

批量--10---根据set数拆分文件

力扣 215. 数组中的第K个最大元素

如何解决QByteArray添加quint16双字节时错误?

Luogu P2437 Bee Route

投资组合分析:portfolio_analysis.Tangenvy_portfolio(切点组合)

论文速读:Homography Loss for Monocular 3D Object Detection

线代005

JDBC再回顾

从头开始实现YOLOV3

2022-08-01:以下go语言代码输出什么?A:panic;B:5;C:6;D:编译错误。 package main import ( “fmt“ ) func main() {
随机推荐
力扣练习——43 路径总和
投资组合分析:portfolio_analysis.Tangenvy_portfolio(切点组合)
抓住那头牛(DAY 96)
Visual SLAM Lecture Fourteen - Lecture 13 Practice: Designing a SLAM system (the most detailed code debugging and running steps)
Learn about the sequential storage structure of binary tree - heap
通关剑指 Offer——剑指 Offer II 008. 和大于等于 target 的最短子数组
ClickHouse的客户端命令行参数
使用 Fastai 构建食物图像分类器
The line chart with square PyQt5_pyqtgraph mouse
康威定律对于系统架构很重要吗?
洛谷P2437蜜蜂路线
线代005
JDBC再回顾
高等数学(第七版)同济大学 总习题三(前10题) 个人解答
Scala基础【常用方法补充、模式匹配】
Digicert EV证书签名后出现“证书对于请求用法无效”的解决方案
【STM32】ADC采集光敏数据(不看库函数手册进行配置)
LeetCode 23: 合并K个升序链表
力扣练习——37 复原IP地址
力扣练习——38 分割回文串