题意:给出两个素数m,n,每次只能变化x中的一个数字,并且变化后的数字也必须是素数,求最少的变化次数
链接:http://poj.org/problem?id=3126
思路:将1000-9999直接的素数表筛选出来,将每一位数字进行广搜
注意点:无
以下为AC代码:
Run ID | User | Problem | Result | Memory | Time | Language | Code Length | Submit Time |
13917604 | luminous11 | 3126 | Accepted | 800K | 16MS | G++ | 2568B | 2015-02-27 22:43:49 |
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;
//const double pi = acos(-1);
//const double eps = 1e-10;
//const int dir[[4][2] = { 1,0, -1,0, 0,1, 0,-1 };
int num[10005];
bool prime[10005];
int m, n;
void init()
{
clr ( prime, 1 );
clr ( num, 0 );
for ( int i = 2; i < 10005; i ++ ){
if ( prime[i] ){
for ( int j = i * i; j < 10005; j += i ){
prime[j] = 0;
}
}
}
cin >> m >> n;
}
int solve()
{
num[m] = 1;
if ( m == n )return num[m];
queue<int> q;
q.push ( m );
while ( ! q.empty() ){
int tmp = q.front();
q.pop();
int a, b, c, d, k;
a = tmp / 1000;
b = tmp / 100 % 10;
c = tmp / 10 % 10;
d = tmp % 10;
for ( int i = 0; i < 10; i ++ ){
k = i * 1000 + b * 100 + c * 10 + d;
if ( prime[k] && num[k] == 0 && k >= 1000 ){
num[k] = num[tmp] + 1;
if ( k == n )return num[k];
q.push ( k );
}
k = a * 1000 + i * 100 + c * 10 + d;
if ( prime[k] && num[k] == 0 && k >= 1000 ){
num[k] = num[tmp] + 1;
if ( k == n )return num[k];
q.push ( k );
}
k = a * 1000 + b * 100 + i * 10 + d;
if ( prime[k] && num[k] == 0 && k >= 1000 ){
num[k] = num[tmp] + 1;
if ( k == n )return num[k];
q.push ( k );
}
k = a * 1000 + b * 100 + c * 10 + i;
if ( prime[k] && num[k] == 0 && k >= 1000 ){
num[k] = num[tmp] + 1;
if ( k == n )return num[k];
q.push ( k );
}
}
}
}
int main()
{
ios::sync_with_stdio( false );
int t;
cin >> t;
while ( t -- ){
init();
cout << solve() - 1 << endl;
}
return 0;
}