poj 3126 Prime Path

 

  题目大意就是输入两个四位数 a,b; 你要以a为起点,每次可以改变四位中任意一位,且每次改变后得到的数要仍然为素数。 问最少要多少步才能变到b,否则输出Impossible。

  每次变换一位,求最少步;所以应该不难得出这是一道典型的bfs题。      先生成素数表1-10000,方便后面判断是否为素数;再开一个标记数组book用来标记出现过的数字。  然后对于输入的a转换为string进行bfs,每次生成新的数字都对其判断是否为素数及是否已出现过。

 

复制代码
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cmath>
 6 #include <cstdlib>
 7 #include <cctype>
 8 #include <queue>
 9 #include <stack>
10 #include <map>
11 #include <vector>
12 #include <set>
13 #include <utility>
14 #define ll long long
15 #define inf 0x3f3f3f3f
16 using namespace std;
17 
18 bool prime[10000];
19 void get_prime() //生成素数表
20 {
21     fill(prime,prime+10000,true);
22     prime[1]=false;
23     for(int i=2; i<=sqrt(10000); i++)
24         if(prime[i])
25             for(int j=i+i; j<10000; j+=i)
26                 prime[j]=false;
27 }
28 int convert(string str)  //将字符串转为数值
29 {
30     return (str[0]-'0')*1000+(str[1]-'0')*100+(str[2]-'0')*10+(str[3]-'0');
31 }
32 typedef pair<string,int> P;
33 string l,r;
34 void solve()
35 {           
36     map<string,int> book;  //标记数组
37     queue<P> q;
38     book[l]=1;
39     q.push(P(l,0));
40     //   BFS
41     while(!q.empty())
42     {
43         P temp=q.front();
44         q.pop();
45         for(int i=0; i<4; i++)
46         {
47             string str=temp.first;
48             for(int j=0; j<=9; j++)
49             {
50                 if(!i&&!j) continue;
51                 //
52                 str[i]='0'+j;
53                 if(str==r)
54                 {
55                     printf("%d\n",temp.second+1);
56                     return;
57                 }
58                 //
59                 if(prime[convert(str)])
60                     if(!book[str])
61                     {
62                         book[str]=1;
63                         P tt;
64                         tt.first=str,tt.second=temp.second+1;
65                         q.push(tt);
66                     }
67             }
68         }
69     }
70     printf("Impossible\n");
71 }
72 int main()
73 {
74     //freopen("input.txt","r",stdin);
75     get_prime();
76     int n;
77     scanf("%d",&n);
78     while(n--)
79     {
80         cin>>l>>r;
81         if(l==r)
82             printf("0\n");
83         else
84             solve();
85     }
86     return 0;
87 }
复制代码

 

posted @   爱喝可乐的咖啡  阅读(231)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示