zoukankan      html  css  js  c++  java
  • cdoj 851 方老师与素数 bfs

    方老师与素数

    Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
     

    方老师最近很喜欢素数,他想玩一个游戏:

    现在有两个44位的素数nn和mm,你一次可以改变nn的一位数字,并且改变过后的新数字必须也是个素数,并且也不能有前导00。请问使nn变为mm最少需要多少步。

    例如n=1033n=1033 m=8179m=8179

    那么可行的变化是:

    1033
    1733
    3733
    3739
    3779
    8779
    8179

    Input

    第一行有一个整数T(T100)T(T≤100),代表测试数据的组数。

    对于每组数据,每行有两个44位素数NMN,M(没有前导00)

    Output

    对于每一组数据,如果能够得到mm,输出最少的步数,否则输出Impossible

    Sample input and output

    Sample InputSample Output
    3
    1033 8179
    1373 8017
    1033 1033
    6
    7
    0

    Source

    2014 UESTC Training for Search Algorithm
     
    #include<bits/stdc++.h>
    using namespace std;
    #define ll long long
    #define pi (4*atan(1.0))
    #define eps 1e-14
    const int N=2e5+10,M=1e6+10,inf=1e9+10,mod=1e9+7;
    const ll INF=1e18+10;
    int p[1110];
    int prime(int n)
    {
        if(n<=1)
        return 0;
        if(n==2)
        return 1;
        if(n%2==0)
        return 0;
        int k, upperBound=n/2;
        for(k=3; k<=upperBound; k+=2)
        {
            upperBound=n/k;
            if(n%k==0)
                return 0;
        }
        return 1;
    }
    int check(int x,int y)
    {
        int sum=0;
        while(x)
        {
            if(x%10!=y%10)sum++;
            x/=10;
            y/=10;
        }
        return sum;
    }
    int flag[10010];
    struct is
    {
        int num;
        int ans;
        is(){}
        is(int x,int y)
        {
            num=x;
            ans=y;
        }
    };
    int main()
    {
        int cnt=0;
        for(int i=1000;i<=10000;i++)
        if(prime(i))
        p[cnt++]=i;
        int T;
        scanf("%d",&T);
        while(T--)
        {
            for(int i=0;i<cnt;i++)
                flag[p[i]]=0;
            int n,m;
            scanf("%d%d",&n,&m);
            flag[n]=1;
            queue<is>q;
            q.push(is(n,0));
            int out=inf;
            while(!q.empty())
            {
                is v=q.front();
                q.pop();
                if(v.num==m)
                {
                    out=v.ans;
                    break;
                }
                for(int i=0;i<cnt;i++)
                {
                    if(!flag[p[i]]&&check(v.num,p[i])==1)
                    {
                        flag[p[i]]=1;
                        q.push(is(p[i],v.ans+1));
                    }
                }
            }
            if(out!=inf)
            printf("%d
    ",out);
            else
                printf("Impossible
    ");
        }
        return 0;
    }
  • 相关阅读:
    MySQL 5.7.18 zip 文件安装过程
    Mysql 自定义随机字符串
    JAVA基本类型和引用类型
    初识JSP
    Java导出错误数据
    时序图的使用习惯
    Redis踩坑
    ES踩坑
    代码规范
    Git在公司的使用流程
  • 原文地址:https://www.cnblogs.com/jhz033/p/5987512.html
Copyright © 2011-2022 走看看