POJ3126 Prime Path

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

题目大意:给两个数四位数m, n, m的位数各个位改变一位0 —— 9使得改变后的数为素数,
问经过多少次变化使其等于n
如:
1033
1733
3733
3739
3779
8779
8179
分析:用字符串存m,n,这样改变各个位较方便

 数组开大一点,开始数组开小了,结果就出错了

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<string.h>
#define max(a, b)(a > b ? a : b)
#define min(a, b)(a < b ? a : b)
#define INF 0xffffff
#define N 10010

using namespace std;

struct node
{
    char s[5];
    int step;
};

char s1[5], s2[5], s3[5];
bool vis[N];

int prime(int n)
{
    int i, k = (int)sqrt(n);
    for(i = 2 ; i <= k ; i++)
        if(n % i == 0)
            return 0;
    return 1;
}

int BFS(char s[])
{
    queue<node>Q;
    node now, next;
    int i, j, h, x = 0;
    memset(vis, false, sizeof(vis));
    memset(s3, 0, sizeof(s3));
    for(i = 0 ; i < 4 ; i++)
        x = x * 10 + (s[i] - '0');
    vis[x] = true;
    strcpy(now.s, s);
    now.step = 0;
    Q.push(now);
    while(!Q.empty())
    {
        now = Q.front();
        Q.pop();
        if(strcmp(now.s, s2) == 0)
            return now.step;
        for(i = 0 ; i < 4 ; i++)
        {
            for(j = 0 ; j < 10 ; j++)
            {
                if((i == 0 && j == 0) || now.s[i] == j + '0')
                    continue;
                strcpy(s3, now.s);
                now.s[i] = j + '0';
                x = 0;
                for(h = 0 ; h < 4 ; h++)
                    x = x * 10 + (now.s[h] - '0');
                if(!vis[x] && prime(x) == 1)
                {
                    vis[x] = true;
                    next.step = now.step + 1;
                    strcpy(next.s, now.s);
                   // i = 0;
                   // j = 0;
                    Q.push(next);
                }
                strcpy(now.s, s3);
            }
        }
    }
    return -1;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s%s", s1, s2);
        printf("%d\n", BFS(s1));
    }
    return 0;
}

 

posted @ 2015-07-20 20:40  午夜阳光~  阅读(146)  评论(0编辑  收藏  举报