POJ 3126 Prime Path

题意:给两个四位数素数X,Y,每次可变换X的一位数字,变换后的数字应为素数,问X变为Y的最小变换次数。

分析:宽度搜索,每次将所有满足条件的,改变X的某一位数的后的素数入队列。

代码:

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstring>
  4 #include <vector>
  5 #include <queue>
  6 #include <cmath>
  7 #include <stack>
  8 #include <set>
  9 #include <map>
 10 #include <algorithm>
 11 using namespace std;
 12 #define ll long long
 13 #define inf 0x3f3f3f3f
 14 int n,m;
 15 struct node
 16 {
 17     int e,t;
 18 };
 19 int v[10001];
 20 bool is(int x)//判断x是否为素数
 21 {
 22     if(x==0||x==1)  return 0;
 23     else if(x==2||x==3)  return 1;
 24     else
 25     {
 26         for(int i = 2;i<=(int)sqrt(x);i++)
 27             if(x%i==0)
 28                 return 0;
 29         return 1;
 30     }
 31 }
 32 int bfs()
 33 {
 34     int i,j,a,b,c,d;
 35     node x,y;
 36     queue<node> q;
 37     x.e=n;x.t=0;
 38     v[x.e]=1;
 39     q.push(x);
 40     while(!q.empty())
 41     {
 42         y=q.front();
 43         q.pop();
 44         if(y.e==m) return y.t;
 45         a=y.e%10;
 46         b=y.e/10%10;
 47         c=y.e/100%10;
 48         d=y.e/1000;
 49         for(i=1;i<=9;i+=2)//保证个位为奇数。
 50         {
 51             if(i!=a)
 52             {
 53                 x.e=y.e-a+i;//个位换为i
 54                 if(is(x.e)&&!v[x.e])
 55                 {
 56                     v[x.e]=1;
 57                     x.t=y.t+1;
 58                     q.push(x);
 59                 }
 60             }
 61         }
 62         for(i=0;i<=9;i++)
 63         {
 64             if(i!=b)
 65             {
 66                 x.e=y.e-b*10+i*10;
 67                 if(is(x.e)&&!v[x.e])
 68                 {
 69                     v[x.e]=1;
 70                     x.t=y.t+1;
 71                     q.push(x);
 72                 }
 73             }
 74         }
 75         for(i=0;i<=9;i++)
 76         {
 77             if(i!=c)
 78             {
 79                 x.e=y.e-c*100+i*100;
 80                 if(is(x.e)&&!v[x.e])
 81                 {
 82                     v[x.e]=1;
 83                     x.t=y.t+1;
 84                     q.push(x);
 85                 }
 86             }
 87         }
 88         for(i=1;i<=9;i++)
 89         {
 90             if(i!=d)
 91             {
 92                 x.e=y.e-d*1000+i*1000;
 93                 if(is(x.e)&&!v[x.e])
 94                 {
 95                     v[x.e]=1;
 96                     x.t=y.t+1;
 97                     q.push(x);
 98                 }
 99             }
100         }
101     }
102     return -1;
103 }
104 int main()
105 {
106     int i,t;
107     scanf("%d",&t);
108     while(t--)
109     {
110         scanf("%d %d",&n,&m);
111         memset(v,0,sizeof v);
112         int k=bfs();
113         if(k!=-1)
114         printf("%d\n",k);
115         else printf("Impossible\n");
116     }
117     return 0;
118 }

 

posted @ 2016-10-17 23:36  Nautilus1s  阅读(124)  评论(0编辑  收藏  举报