欢迎光临散文网 会员登陆 & 注册

机试小课堂丨搜索周·例题讲解②《Prime Path》

2021-01-25 00:27 作者:苏世考研  | 我要投稿


苏世计算机考研,程序猿专属的学习分享社区


【声明:本文为原创文章,未经同意,严禁转载和抄袭,违者将追究其法律责任】


苏世机试小课堂,考研机试不再慌!


公主号:苏世学社考研  苏世计算机考研


Prime Path


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 apositive number: the number of test cases (at most 100). Then for each testcase, one line with two numbers separated by a blank. Both numbers arefour-digit primes (without leading zeros).


Output


One line for each case,either with a number stating the minimal cost or containing the wordImpossible.


Sample Input


   3

   1033 8179

   1373 8017

   1033 1033


Sample Output


   6

   7

   0



答案



①读题:


给出两个四位数a和b,将a变成b需要多少步,要求每个只能改变a的某一位数,即改变后的数和改变前的数只有一位不同,并且每次改变后的数都是素数,且不能重复,求从a变到b最少需要的次数,无法变换就输出Impossible。


②想出思路:


筛选素数+BFS,枚举每一位数字进行修改,如果是素数就进入队列,循环出队队列。


③动手编程:




④测试样例:



⑤提交代码:


进入下面的链接提交核心代码:

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


⑥返回评测结果:



至此,这道题我们就已经完成了。



本题总结


针对这个题,先筛选出数据范围内所有素数,然后BFS搜索,按位来改变数字,并累加算出到该数的变化次数,是素数就加入队列,看看是不是和最终要的数字一样。


未完待续

苏世学社旗下品牌,专注于计算机考研

计算机考研一手资讯,原创高质量干货

深度的学习分享丨咨询前辈丨个性化指导




机试小课堂丨搜索周·例题讲解②《Prime Path》的评论 (共 条)

分享到微博请遵守国家法律