Loading

Prime Path || 继续bfs

 

 

首先也是最短决策。非常适合线性bfs(改个名字)。

就很恶心,代码有点长比较容易出错,然后就是POJ没有c++11,写的直接入土。

主要思路还是比较简单就是说四位数字,分别枚举每一位数字的出边,每一个数字的出边最多有10种情况,辅助函数比较多需要仔细写写,筛质数和check函数都是看的评论区改进了一下的,写这种题我就容易把代码写的太冗长了。

代码 :

 1 #include <iostream>
 2 #include <queue>
 3 #include <cstring>
 4 #include <algorithm>
 5 #define gogo ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
 6 using namespace std;
 7 //using i64 = long long;
 8 //#define endl '\n';
 9 const string YES = "Yes";
10 const string NO = "No";
11 
12 struct Node
13 {
14     int num, dis;
15     Node(int n, int d) : num(n), dis(d) {}
16 };
17 const int N = 10000;
18 int a, b;
19 //prime
20 bool st[N];
21 queue<Node> q;
22 bool is_prime(int x)
23 {
24     for (int i = 2; i <= x / i; i++)
25         if (x % i == 0)
26             return false;
27     return true;
28 }
29 int get(int a, int b, int c, int d) {
30     return a * 1000 + b * 100 + c * 10 + d;
31 }
32 void check(int x, int d) {
33     if (!st[x] && is_prime(x) && (x >= 1000 && x < 10000)) {
34         st[x] = true;
35         q.push(Node(x, d + 1));
36     }
37 }
38 int bfs(int a) {
39     while(q.size())
40         q.pop();
41     q.push(Node(a, 0));
42     memset(st, 0, sizeof st);
43 
44     if (a == b)
45         return 0;
46     while (q.size()) {
47         Node t = q.front();
48         q.pop();
49 
50         int n1 = t.num / 1000, n2 = t.num / 100 % 10, n3 = t.num /10 % 10, n4 = t.num % 10;
51 
52         int s = 0;
53         for (int i = 0;i <= 9;i ++) {
54             s = get(i, n2, n3, n4);
55             if (s == b)
56                 return t.dis + 1;
57             check(s, t.dis);
58 
59             s = get(n1, i, n3, n4);
60             if (s == b)
61                 return t.dis + 1;
62             check(s, t.dis);
63 
64             s = get(n1, n2, i, n4);
65             if (s == b)
66                 return t.dis + 1;
67             check(s, t.dis);
68 
69             s = get(n1, n2, n3, i);
70             if (s == b)
71                 return t.dis + 1;
72             check(s, t.dis);
73         }
74     }
75     return -1;
76 }
77 
78 void run() {
79     cin >> a >> b;
80 
81     int ans = bfs(a);
82     if (ans == -1) 
83         cout << "Impossible" << '\n';
84     else 
85         cout << ans << '\n';
86 }
87 
88 int main() {
89     gogo;
90     int tt;
91     cin >> tt;
92     while (tt --)
93         run();
94 }
View Code

 

posted @ 2023-02-18 22:48  KakaDBL  阅读(24)  评论(0)    收藏  举报