F-PrimePathTimeLimit:1000MSMemoryLimit:65536KB64bitIOFormat:%I64d&%I64uSubmitSta
F -Prime PathTime Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64uSubmitStatusPracticePOJ 3126
Description
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.
Input
One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).
Output
One line for each case, either with a number stating the minimal cost or containing the word Impossible.
Sample Input
3
1033 8179
1373 8017
1033 1033
Sample Output
6
7
0
从一个素数转变到另一个素数,而且中间的数字也得是素数,并且相邻的两个数字只有一位不同,很明显,是一道在素数集合上的搜索题目,并且一定是四位数的素数。
因为本身四位数的素数很少,这里直接打了一个表,当然不是一个一个敲上去,先卸了一个求素数的程序,然后直接粘贴的,如果熟悉文件输入输出的话,也可以用文件来处理。
既然题目要求所经过的路径最短,自然是BFS,关键是BFS构造的问题,有一个很简单的方法,就是把BFS想成一棵树,每个节点表示一个状态,这个节点的子节点则表示由该状态可到达的状态,对于一个四位数,比如1033,它的千位可以从1-9取值,百位和十位可以从0-9取值,而个位只能取奇数位,因为个位为偶数的数肯定不是素数,然后就是让所有可以到达的状态进队列,并且给他们标记,防止下次再次进入,至于判断素数,可以在O(1)内完成,所以整个程序的效率是比较高的。
最后如果弹出的数就是想要到达的数,输出步数
Tips:一般这种要求步数的BFS都是需要使用结构体,每一个节点记录自己的步数
#include
#include
#include
#include
#include
#include