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; }