POJ 3126 Prime Path

  简单的BFS + 素数筛。。。。。手残把素数筛敲错了  调试了大半年......不过终于迎来了久违的 1A

  

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstdlib>
  4 #include <cstring>
  5 #include <cmath>
  6 #include <queue>
  7 
  8 using namespace std;
  9 
 10 bool HashPrime[10010];
 11 bool Mark[10010];
 12 
 13 struct N
 14 {
 15     int p,s;
 16 }t,nt;
 17 
 18 void bfs(int n,int m)
 19 {
 20     int i;
 21     queue<N> q;
 22     t.p = n;
 23     t.s = 0;
 24     q.push(t);
 25     Mark[n] = true;
 26 
 27     while(!q.empty())
 28     {
 29         t = q.front();
 30         q.pop();
 31 
 32         if(t.p == m)
 33         {
 34             printf("%d\n",t.s);
 35             return ;
 36         }
 37         for(i = 1;i < 10; ++i)
 38         {
 39             nt.s = t.s+1;
 40             nt.p = t.p/10*10 + i;
 41 
 42             if(HashPrime[nt.p] == false && Mark[nt.p] == false)
 43             {
 44                 q.push(nt);
 45                 Mark[nt.p] = true;
 46             }
 47         }
 48         for(i = 0;i < 10; ++i)
 49         {
 50             nt.s = t.s+1;
 51             nt.p = t.p/100*100 + t.p%10 + i*10;
 52 
 53             if(HashPrime[nt.p] == false && Mark[nt.p] == false)
 54             {
 55                 q.push(nt);
 56                 Mark[nt.p] = true;
 57             }
 58         }
 59         for(i = 0;i < 10; ++i)
 60         {
 61             nt.s = t.s+1;
 62             nt.p = t.p/1000*1000 + t.p%100 + i*100;
 63 
 64             if(HashPrime[nt.p] == false && Mark[nt.p] == false)
 65             {
 66                 q.push(nt);
 67                 Mark[nt.p] = true;
 68             }
 69         }
 70         for(i = 1;i < 10; ++i)
 71         {
 72             nt.s = t.s+1;
 73             nt.p = t.p%1000 + i*1000;
 74 
 75             if(HashPrime[nt.p] == false && Mark[nt.p] == false)
 76             {
 77                 q.push(nt);
 78                 Mark[nt.p] = true;
 79             }
 80         }
 81     }
 82     printf("Impossible\n");
 83     return ;
 84 }
 85 
 86 int main()
 87 {
 88     int i,j;
 89     memset(HashPrime,false,sizeof(HashPrime));
 90     for(i = 2;i <= 10000; ++i)
 91     {
 92         if(HashPrime[i] == false)
 93         {
 94             for(j = i+i;j <= 10000; j += i)
 95             {
 96                 HashPrime[j] = true;
 97             }
 98         }
 99     }
100 
101     int n,m;
102     int T;
103     scanf("%d",&T);
104     while(T--)
105     {
106         memset(Mark,false,sizeof(Mark));
107         scanf("%d %d",&n,&m);
108         bfs(n,m);
109     }
110 
111     return 0;
112 }

 

你可能感兴趣的:(POJ 3126 Prime Path)