zoukankan      html  css  js  c++  java
  • POJ 3126 Prime Path BFS搜索

    题意:就是找最短的四位数素数路径

    分析:然后BFS随便搜一下,复杂度最多是所有的四位素数的个数

    #include<cstdio>
    #include<algorithm>
    #include<iostream>
    #include<cstring>
    #include<cmath>
    #include<map>
    #include<queue>
    #include<stdlib.h>
    #include<string>
    using namespace std;
    typedef long long LL;
    const int maxn=10005;
    const int INF=0x3f3f3f3f;
    int t,s;
    int a[maxn];
    bool vis[maxn];
    bool fun(int x)
    {
        for(int i=2; i*i<=x; ++i)
            if(x%i==0)return 0;
        return 1;
    }
    struct Data
    {
        int b[4];
    } d,e;
    queue<Data>q;
    int get(Data x)
    {
        int ans=0;
        for(int i=3; i>=0; --i)
            ans=ans*10+x.b[i];
        return ans;
    }
    int main()
    {
        int T;
        for(int i=1001; i<10000; ++i)
            if(fun(i))vis[i]=1;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d%d",&s,&t);
            memset(a,-1,sizeof(a));
            while(!q.empty())q.pop();
            if(!vis[s]||!vis[t])
            {
                printf("Impossible
    ");
                continue;
            }
            a[s]=0;
            for(int i=0; i<4; ++i)
            {
                d.b[i]=s%10;
                s/=10;
            }
            q.push(d);
            while(!q.empty())
            {
    
                e=d=q.front();
                q.pop();
                int k=get(d);
                if(k==t)break;
                for(int i=0; i<4; ++i)
                {
                    for(int j=0; j<10; ++j)
                    {
                        if(j==d.b[i])continue;
                        e.b[i]=j;
                        int x=get(e);
                        if(!vis[x]||a[x]>=0)continue;
                        a[x]=a[k]+1;
                        q.push(e);
                    }
                    e.b[i]=d.b[i];
                }
            }
            if(a[t]==-1)
            {
                  printf("Impossible
    ");
                  continue;
            }
            printf("%d
    ",a[t]);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    Http中的patch
    如何实现腾讯地图的路径规划功能?
    各类数据库分页SQL语法
    ABC222F
    ABC222 G
    LG5308 [COCI2019] Quiz(wqs二分+斜率优化DP)
    [USACO21OPEN] Portals G(Kruskal)
    【做题笔记】SP27379 BLUNIQ
    【做题笔记】CF938C Constructing Tests
    CSP-J/S2021 自闭记
  • 原文地址:https://www.cnblogs.com/shuguangzw/p/5162859.html
Copyright © 2011-2022 走看看