HUT1105 Prime Path BFS

1105: Prime Path

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 2  Solved: 2
[Submit][Status][Web Board]

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
 
  该题是要我们在给定的两个素数之间寻找一条“路径”,这条“路径”就是每次在上一个素数的基础上改变某一位的数字,这个新的数字仍然要求是一个素数,寻找出最小的变换次数能够满足这个要求。例如:1033-> 1733-> 3733-> 3739-> 3779-> 8779-> 8179。
  我们这里用BFS来搜索解,因为该题是要求最少的步数,那么我们就逐步穷举,直至找到那个匹配最后的数为止。为了使用STL中的queue(o(∩∩)o...哈哈,好东西),前面想把一个容量为5个字节的字符数组串作为queue的类型,但是失败了,要是传指针的话,那么其自增性就没有了,因为为了应付外面的重写会改变queue中的值,我必须开辟一个又一个数组...后来定义类型为string,但是记录步数的数据又没法存储到queue中去了,因此,最后还是定义为结构体吧,没事,这东西在C++中再平常不过了。
  代码如下:
#include <cstdio>
#include <iostream>
#include <cmath>
#include <queue>
#include <cstdlib>
#include <cstring>
#define MAX 10000
using namespace std;

char isp[MAX+ 1], hash[MAX+ 1];

struct E
{
	string s;
	int step;
}beg, end;

int endnum;

void Prime(  )
{
	const int lim= sqrt( MAX );
	for( int i= 4; i<= MAX; i+= 2 )
	{
		isp[i]= 1;
	}
	for( int i= 3; i<= lim; i+= 2 )
	{
		int k= 2* i;
		for( int j= i* i; j<= MAX; j+= k )
		{
			isp[j]= 1;
		}
	}
}

int BFS( queue< E >& q )
{
	while( !q.empty() )
	{
		E pos= q.front();
		if( atoi( pos.s.c_str() )== endnum  )
		{
			return 0;
		}
		q.pop();
		for( int i= 3; i>= 0; --i )
		{
			E temp( pos );  // 每次对temp赋初始值为pos所指sting类
			temp.step++;
			temp.s[i]-= '0';
			for( temp.s[i]= ( temp.s[i]+ 1 )% 10 ; temp.s[i]!= pos.s[i]- '0'; temp.s[i]= ( temp.s[i]+ 1 )% 10 )
			{
				temp.s[i]+= '0';
				int num= atoi( temp.s.c_str() );
				if( num< 1000 ) 
				{
					temp.s[i]-= '0';
					continue;
				}
				if( num== endnum )
				{
					return temp.step;
				}
				if( !isp[num]&& !hash[num] )
				{ 
					q.push( temp ); // 该处用到了temp的值,因此temp.s[i]到最后才转化为int型计算
					hash[num]= 1;
				}
				temp.s[i]-= '0';  
			}
		}
	}
}

int main()
{
	Prime();
	int T;
	scanf( "%d", &T );
	while( T-- )
	{
		queue< E > q; // 由于q.clear()不存在, 这样定义,经过一个循环后自动释放
		memset( hash, 0, sizeof( hash ) );
		cin>> beg.s>> end.s;
		beg.step= 0;
		endnum= atoi( end.s.c_str() );
		q.push( beg );
		printf( "%d\n", BFS( q ) );
	}
}
// 重写,多了些面向对象的思想吧,呵呵
#include <cstdlib> #include <cstdio> #include <cstring> #include <iostream> using namespace std; // 一个简单的BFS搜索,注意到状态的转移和记忆化 bool hash[10005], p[10005]; bool G[1070][1075]; int pri[10005], que[10005], beg, end; struct Node { int num; char dig[4]; void build(int); bool pass(Node); }seq[10005]; int cnt = -1, top = -1; void Node::build(int x) { num = x; // 将这个值记录起来 for (int i = 3; i >= 0; --i) { dig[i] = x % 10, x /= 10; // 将每一位进行分离 } } bool Node::pass(Node other) { int cnt = 0; for (int i = 0; i < 4; ++i) { if (dig[i] != other.dig[i]) ++cnt; if (cnt > 1) return false; } return cnt == 1; } void getprime() { for (int i = 2; i < 10000; ++i) { if (!p[i]) { pri[++cnt] = i; } for (int j = 0; pri[j] * i < 10000; ++j) { p[pri[j] * i] = 1; if (i % pri[j] == 0) { break; } } } for (int i = 0; i <= cnt; ++i) { if (pri[i] > 1000) { seq[++top].build(pri[i]); } } } int BFS() { int front = 0, tail = 0; que[++tail] = beg * 2000; hash[beg] = 1; while (front != tail) { int box = que[++front], pos = box / 2000; for (int i = 0; i <= top; ++i) { if (G[pos][i] && !hash[i]) { if (i == end) { return box % 2000 + 1; } hash[i] = 1; que[++tail] = i * 2000 + box % 2000 + 1; } } } return -1; } int main() { memset(hash, 0, sizeof (hash)); memset(p, 0, sizeof (p)); memset(G, 0, sizeof (G)); getprime(); for (int i = 0; i <= top; ++i) { for (int j = 0; j <= top; ++j) { G[i][j] = seq[i].pass(seq[j]); } } int T, A, B, ret; scanf("%d", &T); while (T--) { scanf("%d %d", &A, &B); if (A == B) { puts("0"); continue; } memset(hash, 0, sizeof (hash)); for (int i = 0; i <= top; ++i) { if (seq[i].num == A) beg = i; if (seq[i].num == B) end = i; } if ((ret = BFS()) != -1) { printf("%d\n", ret); } else { puts("Impossible"); } } return 0; }
原文地址:https://www.cnblogs.com/Lyush/p/2121237.html