Prime Path (HDU1973/POJ3126)(B)

来源:互联网 发布:线性时间选择算法分析 编辑:程序博客网 时间:2024/06/08 06:45

どこでもドア:http://acm.hdu.edu.cn/showproblem.php?pid=1973
どこでもドア:http://poj.org/problem?id=3126

输入一个t表示有t组数据,每组数据输入2个数,这两个数字是四位的素数(不包括前导零)。
每次只能变换一位数字,且变换后的4位数也是素数,问最少变多少次才能变成从第一个数变为第二个数。
例:
1033
1733
3733
3739
3779
8779
8179
答案:6

AC CODE:

#include<iostream>#include<cstdio>#include<algorithm>#include<cmath>#include<cstring>#include<string>#include<sstream>#include<set>#include<cstdlib>#include<map>#include<queue>#include<fstream>using namespace std;typedef long long LL;const int M=10000;bool prime[M];int base[3] = {1,10,100};int main(){    //打表判断素数    for(int i = 0; i < M; i++)        prime[i] = 1;    for(int i = 2; i < M; i++)    {        if(prime[i])        {            for(int j = 2; i*j < M; j++)                prime[i*j] = 0;        }    }    int T,n,m,ans[M],d[4];    scanf("%d",&T);    while(T--)    {        memset(ans,0,sizeof(ans));        int fr;        scanf("%d%d",&n,&m);        queue<int> que;        ans[n]=1;    //ans记录变换的次数,且能用来判断是否访问过        que.push(n);  //下面bfs        while(!que.empty())        {            fr=que.front();            que.pop();            if(fr==m)            {                cout<<ans[fr]-1<<endl;   //初始值为了来判断是否访问过赋值为1,这里-1表示记录的变化的次数。                break;            }            //记录个,十,百3位上的数字,为了之后从原数中去掉要变化的位数            d[0] = fr%10;            d[1] = fr%100/10;            d[2] = fr%1000/100;            int x;            for(int i = 0; i < 10; i ++)//能替换的数字0-9            {                //分别变换千 百 十 个位上的数字,由于千位不能为0所以单独写                //x是变化后的数字                x = fr - fr/1000*1000 + i*1000;                if(i != 0 && prime[x] && !ans[x]){                    ans[x] = ans[fr] + 1;                    que.push(x);                }                //变化后三位用循环简化代码                for(int k = 0; k < 3; k++)                {                    x = fr - d[k]*base[k] + i*base[k];                    if(prime[x] && !ans[x]){                        ans[x] = ans[fr] + 1;                        que.push(x);                    }                }            }        }    }    return 0;}
0 0
原创粉丝点击