POJ 3126 Prime Path BFS Solution

Source: Internet
Author: User

Topic Connection: http://poj.org/problem?id=3126

Test instructions: Given two prime numbers, find the shortest prime number path between the two.


This problem with a single bfs is enough, but, or practice the double BFS.


Code:


#include <iostream> #include <sstream> #include <cstring> #include <cstdio> #include <cmath
> #include <algorithm> #include <queue> #include <set> #include <map> #include <vector>

#include <string> #define LL __int64 #define INF 0xFFFFFFFF using namespace std;

struct node{int x,step;};

int prime[10000],vis[2][10000],m,n;
    void Init () {memset (prime,0,sizeof (prime));p rime[0]=prime[1]=1;
for (int i=2;i< (int) sqrt (100000.5), i++) if (!prime[i]) for (int j=i*i;j<10000;j+=i) prime[j]=1;
    } void BFs () {memset (vis,0,sizeof (VIS));
    Queue<node> q[2]; Q[0].push (node) {m,0});
    Q[1].push (node) {n,0});
    Vis[0][m]=1;vis[1][n]=1;
    int deep=0; while (! Q[0].empty () | | !
        Q[1].empty ()) {int i=0;
            while (I&LT;2) {node Tp=q[i].front ();
            if (tp.step!=deep) {i++;continue;}
            Q[i].pop (); int t[4];//gets each digit t[0]=tp.x%10;
  t[1]= (TP.X/10)%10;          t[2]= (tp.x/100)%10;
            T[3]= (tp.x/1000);
                for (int j=0;j<4;j++) {//change position int y=0;
                    for (int k=3;k>=0;k--)//place the position that needs to be changed to 0 if (k!=j) y=y*10+t[k];
                else y=y*10;
                    for (int k=0;k<10;k++) {//enum change the value of the position int ty=y+k* (int) pow (10,j);
                    if (Vis[1-i][ty]) {cout<< (deep*2+i+1) <<endl;return;}
                    if (Vis[i][ty] | | prime[ty] | | ty<1000) continue;
                    Q[i].push (node) {ty,deep+1});
                Vis[i][ty]=1;
    }}} deep++;
    }} int main () {init ();
    int t;cin>>t;
        while (t--) {scanf ("%d%d", &m,&n);
        if (m==n) {cout<<0<<endl;continue;}
    BFS ();
} return 0;
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.