Prime Path

Prime Path

 POJ - 3126 

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<algorithm>
  4 #include<cstring>
  5 #include<queue>
  6 using namespace std;
  7 
  8 int n,m;
  9 bool book[100005];
 10 //bool prime[10005];
 11 struct note
 12 {
 13     int x;
 14     int s;
 15 }a,b;
 16     
 17 bool prime(int v) // Prime sieve will not. . So used this. Fortunately, the data is small 
18  {
 19      for ( int i= 2 ;i*i<=v;i++ )
 20      {
 21          if (v%i== 0 ) return  false ;
 22      }
 23      return  true ;
 24  }
 25  
26  void bfs ()
 27  {
 28      queue<note> q;
 29  
30      book[n]= 1 ;
 31      ax= n;
 32      as=0;
 33     q.push(a);
 34     while(!q.empty())
 35     {
 36         a=q.front();
 37         q.pop();
 38         
 39         if(a.x==m)
 40         {
 41             cout<<a.s<<endl;
 42             return;
 43         }
 44         
 45         for(int i=1;i<=9;i+=2)//
 46         {
 47             bx=ax/ 10 * 10 + i;
 48              bs=a.s+ 1 ; // Should this step be placed in the following if? ? 
49              if (book[bx]== 0 && prime(bx))
 50              {
 51                  book[bx]= 1 ;
 52                  q.push(b);
 53              }
 54          }
 55          for ( int i= 0 ;i<= 9 ;i++) // ten 
56          {
 57             b.x=a.x/100*100+ 10*i + a.x%10;
 58             b.s=a.s+1;
 59             if(book[b.x]==0&&prime(b.x))
 60             {
 61                 book[b.x]=1;
 62                 q.push(b);
 63             }
 64         }
 65         for(int i=0;i<=9;i++)//
 66         {
 67             b.x=a.x/1000*1000+ 100*i + a.x%100;
 68             b.s=a.s+1;
 69             if(book[b.x]==0&&prime(b.x))
 70             {
 71                 book[b.x]=1;
 72                 q.push(b);
 73             }
 74         }
 75         for(int i=1;i<=9;i++)//
 76         {
 77             b.x=1000*i+ a.x%1000;
 78             b.s=a.s+1;
 79             if(book[b.x]==0&&prime(b.x))
 80             {
 81                 book[b.x]=1;
 82                 q.push(b);
 83             }
 84         }
 85     }
 86     cout<<"Impossible"<<endl;
 87     return;
 88 }
 89 
 90 int main()
 91 {
 92     /*memset(prime,0,sizeof(prime));  
 93     for(int i=2;i<=110;i++){   //筛素数  
 94         if(prime[i]==0)  
 95             for(int j=i+i;j<10010;j+=i){  
 96                 prime[j]=1;  
 97             }  
 98     } */
 99     
100     int T;
101     cin>>T;
102     while(T--)
103     {
104         memset(book,0,sizeof(book));
105         cin>>n>>m;
106         bfs();
107     }
108 }

Attach the sieve prime method     https://www.cnblogs.com/grubbyskyer/p/3852421.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325283498&siteId=291194637