• POJ


    题目链接:https://vjudge.net/problem/POJ-3126

    从一个素数到另一个素数,每一步只能改变一个数,途径的数也必须是素数,求最小步数。

    AC代码:

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstring>
     4 #include<cstdio>
     5 #include<cmath>
     6 #include<stack>
     7 #include<queue>
     8 
     9 using namespace std;
    10 typedef long long ll;
    11 const int maxn = 2e6 + 5;
    12 const int INF = 0x3f3f3f3f;
    13 
    14 bool isPrime[10005];
    15 int vis[10005];
    16 int prime[10005];
    17 
    18 void Prime(int R)
    19 {
    20     memset(isPrime, 0, sizeof(isPrime));
    21     memset(prime, 0, sizeof(prime));
    22     for (int i = 2; i <= R; i++) {
    23         if (!isPrime[i]) {
    24             prime[++prime[0]] = i;
    25         }
    26         for (int j = 1; j <= prime[0] && i * prime[j] <= R; j++) {
    27             isPrime[i * prime[j]] = 1;
    28             if (i % prime[j] == 0) break;
    29         }
    30     }
    31 }
    32 
    33 struct node
    34 {
    35     int num;
    36     int step;
    37 };
    38 
    39 int st, ed;
    40 
    41 int bfs(int st)
    42 {
    43     queue<node>qe;
    44     node start, next;
    45     start.num = st;
    46     start.step = 0;
    47     memset(vis, 0, sizeof(vis));
    48     qe.push(start);
    49     while (!qe.empty()) {
    50         node temp = qe.front();
    51         qe.pop();
    52         if (temp.num == ed) {
    53             return temp.step;
    54         }
    55         vis[temp.num] = 1;
    56         for (int k = 0; k < 4; k++) {
    57             int head = 0;
    58             int x = (int)pow(10.0, k);
    59             head = temp.num - (temp.num / x % 10) * x;
    60             for (int i = 0; i <= 9; i++) {
    61                 if (x == 1000 && i == 0) continue;
    62                 next.num = head + i * x;
    63                 if (next.num > 9999) break;
    64                 if (!isPrime[next.num] && !vis[next.num]) {
    65                     next.step = temp.step + 1;
    66                     qe.push(next);
    67                     vis[next.num] = 1;
    68                 }
    69             }
    70         }
    71     }
    72     return -1;
    73 }
    74 
    75 int main()
    76 {
    77     Prime(10001);
    78     int t;
    79     cin >> t;
    80     while (t--)
    81     {
    82         cin >> st >> ed;
    83         int ans = bfs(st);
    84         cout << ans << endl;
    85     }
    86     return 0;
    87 }
  • 相关阅读:
    我的git笔记
    我的 Sublime Text 2 笔记
    在Windows系统配置Jekyll
    纯CSS3打造七巧板
    JavaScript原型之路
    基于Grunt构建一个JavaScript库
    How React Works (一)首次渲染
    hadoop2.4 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    pyinstaller打包python源程序访问hive
    hadoop balance均衡datanode存储不起作用问题分析
  • 原文地址:https://www.cnblogs.com/zny0222/p/13925927.html
Copyright © 2020-2023  润新知