zoukankan      html  css  js  c++  java
  • 【Poj3126】【BNUOJ3245】Prime Path

    http://poj.org/problem?id=3126

    https://www.bnuoj.com/v3/problem_show.php?pid=3245

    题目鬼图

    刚开始看到题目的图觉得这题会很鬼,然后看题,发现是水题。。。

    线性筛预处理素数→BFS+记录深度 or 迭代加深 or 分层BFS

    // <3126.cpp> - 11/01/16 17:31:53
    // This file is made by YJinpeng,created by XuYike's black technology automatically.
    // Copyright (C) 2016 ChangJun High School, Inc.
    // I don't know what this program is.
    
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <cstring>
    #include <cstdio>
    #include <cstdlib>
    #include <cmath>
    #include <queue>
    using namespace std;
    typedef long long LL;
    const int MAXN=10010;
    inline int gi() {
    	register int w=0,q=0;register char ch=getchar();
    	while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    	if(ch=='-')q=1,ch=getchar();
    	while(ch>='0'&&ch<='9')w=w*10+ch-'0',ch=getchar();
    	return q?-w:w;
    }
    queue<int>q;int f[MAXN],t[11];bool prime[MAXN];
    int bfs(int u,int v){
        if(u==v)return 0;
        while(!q.empty())q.pop();
        q.push(u);
        memset(f,0,sizeof(f));
        while(!q.empty()){
            int x=q.front();q.pop();
            t[0]=x/1000;t[1]=x%1000/100;t[2]=x%100/10;t[3]=x%10;
            for(int i=0;i<4;i++){
                int g=t[i];
                for(int j=i==0?1:0;j<=9;j++)
                    if(j!=g){
                        t[i]=j;
                        int k=t[0]*1000+t[1]*100+t[2]*10+t[3];
                        if(!f[k]&&!prime[k]){
                            f[k]=f[x]+1;q.push(k);
                            if(k==v)return f[k];
                        }
                    }
                t[i]=g;
            }
        }
        return -1;
    }
    int main()
    {
    	freopen("3126.in","r",stdin);
    	freopen("3126.out","w",stdout);
        prime[1]=1;
        for(int i=2;i<MAXN;i++)
            if(!prime[i])
                for(int j=i+i;j<MAXN;j+=i)prime[j]=1;
        int t=gi();
        while(t--){
            int u=gi(),v=gi(),ans=bfs(u,v);
            if(ans==-1)printf("Impossible
    ");else printf("%d
    ",ans);
        }
    	return 0;
    }
  • 相关阅读:
    centos7添加firewalld规则
    centos7安装redis5
    Oracle 监听
    创建Oracle表空间及用户
    nginx+keepalive
    oracle 修改端口
    Oracle新建数据库
    Redhat7.5安装JBOSS4.2.0
    kubernetes的一些基本命令
    安装python3.6后使用pip报错
  • 原文地址:https://www.cnblogs.com/YJinpeng/p/6020849.html
Copyright © 2011-2022 走看看