zoukankan      html  css  js  c++  java
  • 搜索------prime path

    给定两个数a,b,每次只能变动a的其中一个数,变成的数也必须是素数,问最少经过几次可以变成b;

    ----------------------------------------------------------------------------------------------

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<queue>
    #include<stack>
    using namespace std;
    #define MAXV 11000
    bool prime[MAXV];
    void init()//判断是否素数
    {
        int i,j;
        for(i=1000; i<=MAXV; i++)
        {
            for(j=2; j<i; j++)
                if(i%j==0)
                {
                    prime[i]=false;
                    break;
                }
            if(j==i) prime[i]=true;
        }
    }
    int bfs(int first,int last)
    {
        bool dis[MAXV];
        queue <int>q;
        int v,i,j,temp,vtemp,count[MAXV],t[4];
        memset(dis,false,sizeof(dis));
        memset(count,0,sizeof(count));
    
        q.push(first);
        dis[first]=true;
    
        while(!q.empty())
        {
            v=q.front();
            q.pop();
    
            t[0]=v/1000;
            t[1]=v%1000/100;
            t[2]=v%100/10;
            t[3]=v%10;
    // printf("%d %d %d %d",t[0],t[1],t[2],t[3]);
    
            for(j=0; j<4; j++)
            {
                temp=t[j];
                for(i=0; i<10; i++)
                    if(i!=temp)
                    {
                        t[j]=i;
                        vtemp=t[0]*1000+t[1]*100+t[2]*10+t[3];
                        if(!dis[vtemp] && prime[vtemp])
                        {
                            count[vtemp]=count[v]+1;
                            dis[vtemp]=true;
                            q.push(vtemp);
                        }
                        if(vtemp==last) return count[vtemp];
                    }
                t[j]=temp;
            }
            if(v==last) return count[v];
        }
        return -1;
    }
    int main()
    {
        int n,a,b,key;
        init();
        scanf("%d",&n);
        while(n--)
        {
            scanf("%d%d",&a,&b);
            key=bfs(a,b);
            if(key!=-1) printf("%d
    ",key);
            else printf("Impossible
    ");
        }
        return 0;
    }
  • 相关阅读:
    caml library
    DIV+CSS 最常用知识
    Jquery(Ajax) 调用 SharePoint 2013 Search Rest API 并使用Josn反回结果并简单显示
    SharePoint 使用Jquery
    SharePoint 报表
    在SharePoint 平台上发布一个Power BI 报表
    Sharepoint前端
    .net 高并发 多消费者模式处理订单
    ERP 系统数据库设计规范
    ListView 点击加载更多
  • 原文地址:https://www.cnblogs.com/biu-biu-biu-/p/5683402.html
Copyright © 2011-2022 走看看