Skip to content

Instantly share code, notes, and snippets.

@buyoh
Created August 5, 2016 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buyoh/d67ca802ad948577a985bcc725855e10 to your computer and use it in GitHub Desktop.
Save buyoh/d67ca802ad948577a985bcc725855e10 to your computer and use it in GitHub Desktop.
捻りはありません
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int m,n;
int ip,iq;
bool nonprime[100001];
void makeprime(int high){
int i,j;
nonprime[0]=true;
nonprime[1]=true;
for (i=2;i<=high;i++){
if (!nonprime[i]){
for (j=i*2;j<=high;j+=i){
nonprime[j]=true;
}
}
}
}
int main(){
int i,j,k,l;
cin>>ip>>iq;
makeprime(iq);
queue<pair<int,int>> q;
q.push(make_pair(ip,0));
int t,e,cnt,digit;
while (!q.empty()){
e =q.front().first;
cnt=q.front().second;
q.pop();
if (e==iq){
l_final:
cout<<cnt<<endl;
return 0;
}
int digit=1;
while (digit<e)digit*=10;
// rightpush
for (i=1;i<10;i++){
t=e*10+i;
if (t==iq) {cnt++;goto l_final;}
if (t<=iq && !nonprime[t]){
q.push(make_pair(t,cnt+1));
nonprime[t]=true;
}
}
if (e>=10){
// rightpop
t=e/10;
if (t==iq) {cnt++;goto l_final;}
if (t<=iq && !nonprime[t]){
q.push(make_pair(t,cnt+1));
nonprime[t]=true;
}
t=e%(digit/10);
if (t/(digit/100)){
// leftpop
if (t==iq) {cnt++;goto l_final;}
if (t<=iq && !nonprime[t]){
q.push(make_pair(t,cnt+1));
nonprime[t]=true;
}
}
}
//leftpush
for (i=1;i<10;i++){
t=e+i*digit;
if (t==iq) {cnt++;goto l_final;}
if (t<=iq && !nonprime[t]){
q.push(make_pair(t,cnt+1));
nonprime[t]=true;
}
}
}
cout<<-1<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment