基本都是一样的套路!!!!!!!!所以加深熟练度!!!!!!!!
部分题目如下:所有数都要求为素数,每次替换某一位数,得到目标数。
— 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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 1e4+5;
const int INF = 0x3f3f3f3f;
int is_prime[maxn];
int vis[maxn];
char chage[10] = {'0','1','2','3','4','5','6','7','8','9'};
struct node
{
char anum[10];
int step;
}s,e;
queue<node> que;
void prime() //1000-10000素数打表
{
is_prime[1] = 1;
for(int i = 2; i < maxn; i++)
{
if(!is_prime[i])
for(int j = 2*i; j < maxn; j+=i)
is_prime[j] = 1;
}
}
int getnum(char *a) //字符数组转成数
{
int temp = 0;
for(int i = 0; i < strlen(a); i++)
temp = temp*10+a[i]-'0';
return temp;
}
void bfs()
{
queue<node> que;
s.step = 0;
que.push(s);
vis[getnum( s.anum) ] = 1; //经过的点标记,避免个回头
node next,temp;
while(!que.empty())
{
temp = que.front();
//cout<<temp.anum<<endl;
que.pop();
if(getnum(temp.anum) == getnum(e.anum))
{
cout<<temp.step<<endl;
return ;
}
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 4; j++)
{
next = temp;
next.anum[j] = chage[i];
int item = getnum( next.anum);
if(!vis[item] && !is_prime[item] && item > 999 && item < 10000)
{
next.step = temp.step +1;
vis[item] = 1;
que.push(next);
}
}
}
}
cout<<"Impossible"<<endl;
return ;
}
int main()
{
memset(is_prime,0,sizeof is_prime); // 等于0表示是素数
prime();
int n;
cin>>n;
while(n--)
{
memset(vis,0,sizeof vis); //等于0表示没经过
scanf("%s %s",s.anum,e.anum);
bfs();
}
return 0;
}