1. 程式人生 > >POJ 3126 Prime Path【從一個素數變為另一個素數的最少步數/BFS】

POJ 3126 Prime Path【從一個素數變為另一個素數的最少步數/BFS】

lan mem 奇數 offices ring finance primes iostream int

Prime Path
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 26475 Accepted: 14555
Description

The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.
— It is a matter of security to change such things every now and then, to keep the enemy in the dark.

— But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
— I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door.
— No, it’s not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime!
— I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds.
— Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime.

Now, the minister of finance, who had been eavesdropping, intervened.

— No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
— Hmm, in that case I need a computer program to minimize the cost. You don‘t know some very cheap software gurus, do you?
— In fact, I do. You see, there is this programming contest going on... Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.
Input

One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).
Output

One line for each case, either with a number stating the minimal cost or containing the word Impossible.
Sample Input

3
1033 8179
1373 8017
1033 1033
Sample Output

6
7
0
Source

Northwestern Europe 2006

【題意】:給你兩個素數,s和e,要求在最少次數從s轉變到e,而且中間的數字也得是素數,並且變化前後相鄰的兩個數只有一位不同
【分析】:是一道在素數集合上的搜索題目,並且一定是四位數的素數。題目要求所經過的路徑最短,自然是BFS。關鍵是BFS構造的問題,有一個很簡單的方法,就是把BFS想成一棵樹,每個節點表示一個狀態,這個節點的子節點則表示由該狀態可到達的狀態,對於一個四位數,比如1033,它的千位可以從1-9取值,百位和十位可以從0-9取值,而個位只能取奇數位,因為個位為偶數的數肯定不是素數,然後就是讓所有可以到達的狀態進隊列,並且給他們標記,防止下次再次進入,至於判斷素數,可以在O(1)內完成,所以整個程序的效率是比較高的。
最後如果彈出的數就是想要到達的數,輸出步數
Tips:一般這種要求步數的BFS都是需要使用結構體,每一個節點記錄自己的步數
【代碼】:

#include<cstdio>
#include<string>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
#include<map>
#include<cctype>
#include<stack>
#include<sstream>
#include<list>
#include<assert.h>
#include<bitset>
#include<numeric>
#define debug() puts("++++")
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a,b,sizeof(a))
#define sz size()
#define be begin()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
#define all 1,n,1
#define rep(i,n,x) for(int i=(x); i<(n); i++)
#define in freopen("in.in","r",stdin)
#define out freopen("out.out","w",stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e18;
const int maxn = 1e3 + 20;
const int maxm = 1e6 + 10;
const int N = 1e4+10;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int dx[] = {-1,1,0,0,1,1,-1,-1};
const int dy[] = {0,0,1,-1,1,-1,1,-1};
int dir[][3]={ {0,0,1},{0,0,-1},{1,0,0},{-1,0,0},{0,1,0},{0,-1,0} };
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

struct node
{
    int p[4],step;
}st,ed;

int vis[15000];
int t,n,s,e;
int a,b,c,d;

bool prime( int x )
{
    for(int i=2; i<=sqrt(x); i++)
        if(x%i==0)
            return false;
    return true;
}

int cal(int *a)
{
    return a[0]*1000 + a[1]*100 + a[2]*10 + a[3];
}

void bfs()
{
    memset(vis,false,sizeof(vis));
    queue<node>q;
    while(!q.empty()) q.pop();

    st.p[0]=s/1000; st.p[1]=s/100%10; st.p[2]=s/10%10; st.p[3]=s%10;
    st.step=0;
    q.push(st);
    vis[cal(st.p)] = 1;

    while(!q.empty())
    {
        st = q.front();
        q.pop();
        if(cal(st.p)==e)
        {
            printf("%d\n",st.step);
            return ;
        }
        for(int i=0;i<4;i++)
        {

            for(int j=0; j<10; j++)
            {
                ed=st;//
                if(i==0 && j==0) continue; //首位不能為0
                ed.p[i]=j; //給某位賦值
                if(!vis[cal(ed.p)] && prime(cal(ed.p)))
                {
                    vis[cal(ed.p)] = 1;
                    ed.step = st.step + 1;
                    q.push(ed);
                }
            }

        }
    }
   printf("Impossible\n");
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&s,&e);
        bfs();
    }
}
/*
3
1033 8179
1373 8017
1033 1033

6
7
0
*/

POJ 3126 Prime Path【從一個素數變為另一個素數的最少步數/BFS】