The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.
— It is a matter of security to change such things every now and then, to keep the enemy in the dark.
— But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
— I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door.
— No, it’s not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime!
— I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds.
— Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime.
Now, the minister of finance, who had been eavesdropping, intervened.
— No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
— Hmm, in that case I need a computer program to minimize the cost. You don’t know some very cheap software gurus, do you?
— In fact, I do. You see, there is this programming contest going on… Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above.
1033
1733
3733
3739
3779
8779
8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.
http://poj.org/problem?id=3126
题意:
从一个四位数变成另一个四位数,每次只能变一位数,且每次变的都是质数
tip:
打个素数表。
变换无非4个位置,函数统一处理一下
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1e5+10;
//int add[10] = {-10,10,1,-1,100,-100,1000,-1000};
int l,r,step[maxn],is_prime[maxn];
void isprim(){
for(int i = 0; i < maxn;i++)
is_prime[i] = true;
is_prime[0] = is_prime[1] = false;
for(int i = 2; i < maxn; i++){
if(is_prime[i]){
for(int j = 2 * i; j <= maxn; j += i)
is_prime[j] = false;
}
}
}
int sov(int i,int j,int tmp){
int x = tmp,re;
if(i == 1){
re = x/10*10+j;
}
if(i == 2){
int y = x %10;
x /= 100;
re = x*100+j*10+y;
}
if(i == 3){
int y = x%100;
x /= 1000;
re = x*1000+j*100+y;
}
if(i == 4){
int y = x%1000;
re = j*1000+y;
}
return re;
}
bool used[maxn];
void bfs(){
queue<int>q;
used[l] = true;
step[l] = 0;
q.push(l);
while(!q.empty()){
int tmp = q.front();
q.pop();
if(tmp == r) return;
for(int i = 1 ; i <= 4 ;i++){
for(int j = 0; j <= 9; j++){
int nx = sov(i,j,tmp);
//cout << nx<<endl;
if(!used[nx]){
used[nx] = true;
if(nx >=1000 && nx < 10000&&is_prime[nx] == true){
step[nx] = step[tmp]+1;
q.push(nx);
}
}
}
}
}
}
int main(){
int T;
isprim();
scanf("%d",&T);
for(int ca = 0 ; ca < T ;ca++){
scanf("%d%d",&l,&r);
memset(used,false,sizeof(used));
bfs();
printf("%d\n",step[r]);
}
}