当前位置:网站首页>质数路径(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;
}
边栏推荐
猜你喜欢
CaDDN code debugging
Excel如何解密工作表保护
PDF文件转换格式
The line chart with square PyQt5_pyqtgraph mouse
internship:数据库表和建立的实体类及对应的枚举类之间的联系示例
1318_将ST link刷成jlink
Live | 7.30 ApacheCon Asia 2022 IOT/IIOT topic, IoTDB PMC Qiao Jialin as the producer
日本痴汉打赏女主播1.5亿,结果。。。
Arduino框架下 ESP32看门狗使用示例
PyQt5_pyqtgraph mouse draws straight lines on line charts
随机推荐
压缩包密码如何快速删除?
开放原子开源峰会落幕,百度超级链牵头成立XuperCore开源工作组
力扣练习——43 路径总和
Qt编写物联网管理平台49-设备模拟工具
ROS visualization of 3D target detection
Deep Blue Academy - Handwritten VIO Homework - Chapter 2
How to decrypt worksheet protection in Excel
6个月测试经验,面试跳槽狮子大开口要18K,只会点点点,给我整无语了。。
应用pca和K-means实现用户对物品类别的喜好细分划分
投资组合分析:portfolio_analysis.Tangenvy_portfolio(切点组合)
跑通CogView教程
【C语言程序】求直角三角形边长
面试官:大量请求 Redis 不存在的数据,从而打倒数据库,有什么方案?
Anatomy of Unreal Playback System (Part 1)
7亿听众背后的在线音频掘金故事
WordPress是什么?我也想用 WordPress~
【云原生】DevOps 新纪元 | 史前的惨淡现实
UI自动化测试框架搭建——标记性能较差用例
2022 Huawei Software Elite Challenge (Preliminary) - Summary
爬虫_爬取wasde月度供需平衡表(实例)