• 素数路(prime) (BFS)


    问题 C: 素数路(prime)

    时间限制: 1 Sec  内存限制: 64 MB
    提交: 8  解决: 5
    [提交][状态][讨论版]

    题目描述

    已知一个四位的素数,要求每次修改其中的一位,并且要保证修改的结果还是一个素数,还不能出现前导零。你要找到一个修改数最少的方案,得到我们所需要的素数。
    例如把1033变到8179,这里是一个最短的方案:
    1033
    1733
    3733
    3739
    3779
    8779
    8179
    修改了6次。

    输入

    1行,两个四位的素数(没有前导零),表示初始数和目标数。

    输出

    一个数,表示最少的操作次数。如果不可能,输出“Impossible”。

    样例输入

    1033 8179
    

    样例输出

    6
    【水题】还是简单的BFS一下。
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    #include <time.h>
    #include <string>
    #include <map>
    #include <stack>
    #include <vector>
    #include <set>
    #include <queue>
    #define inf 0x3f3f3f3f
    #define mod 1000000007
    typedef long long ll;
    using namespace std;
    const int N=100010;
    int n,dp[N],len,m;
    int w[21][21];
    int g[3];
    int flag=0;
    int vis[10000]={0};
    string str[21],ch;
    int maxn=1;
    map<string,int>p,pp;
    struct man
    {
        int x,step;
    };
    int charge(int y)
    {
        for(int ii=2;ii<=sqrt(y);ii++)
        {
            if(y%ii==0)return 0;
        }
        return 1;
    }
    void bfs()
    {
        queue<man>q;
        man s;s.step=0;s.x=n;
       q.push(s);
       vis[n]=1;
       while(!q.empty())
       {
           man t=q.front();
           q.pop();
           //printf("%d %d
    ",t.x,t.step);
           if(t.x==m){flag=1;
            cout<<t.step<<endl;return;
           }
           int a[5];a[4]=t.x/1000;a[3]=t.x/100%10;a[2]=t.x/10%10;a[1]=t.x%10;
           for(int i=1;i<5;i++)
           {
               for(int j=0;j<=9;j++)
               {
                   if(i==4&&j==0)continue;
                   int k=t.x-a[i]*pow(10,i-1)+j*pow(10,i-1);
                   //printf("%d %d
    ",k,charge(k));
                   if(charge(k)==1&&vis[k]==0)
                   {
                       vis[k]=1;
                       man K;
                       K.x=k;K.step=t.step+1;
                       q.push(K);
                   }
               }
           }
       }
    }
     
    int main() {
        memset(w,0,sizeof(w));
        cin>>n>>m;
       bfs();
       if(flag==0)puts("Impossible");
        return 0;
    }
    View Code

  • 相关阅读:
    An Introduction to the Linuxbased Assignments
    [读书笔记]Binary Hancks(1)
    haneWIN NFS Server
    [读书笔记]Binary Hancks(2) livepatch在X86下的实践
    CTNG编译错误以及解决办法
    [转]ucLinux下sqlite数据库移植全攻略
    程序员该有的艺术气质—SOLID原则
    Httpclient远程调用WebService示例(Eclipse+httpclient)
    四种生成和解析XML文档的方法详解(介绍+优缺点比较+示例)
    全网首发:原创SQL数据库同步工具
  • 原文地址:https://www.cnblogs.com/jianrenfang/p/5719846.html
Copyright © 2020-2023  润新知