题目大意:
素数路径
估计看数据就明白这道题什么意思了......给两个素数,都是四位数的素数,并且没有前导0,现在需要经过一种变换把一个素数转换成另一个,当然这种转换是有规则的,规则就是每次只能改变这个四位数的其中一位数字,当然改变后的数字也得是素数,问最少的改变次数是多少......
貌似还是广搜..............................................................................................不过做起来应该会麻烦点,要求素数,不过可以搞一个素数表这样判断起来更方便
#include<stdio.h>
#include< string.h>
#include<math.h>
#include<queue>
using namespace std;
#define maxn 10000
int p[maxn]; // 标记4位数的素数
int Prime( int n)
{
int i, k=sqrt(n);
for(i= 2; i<=k; i++)
if(n % i == 0)
return 0;
return 1;
}
int Turn( int n, int k) // 把n的第k位转换成0
{
char s[ 10]={ 0};
sprintf(s, " %d ", n);
s[k] = ' 0 ';
sscanf(s, " %d ", &n);
return n;
}
int BFS( int s, int e)
{
int i, j, k, q;
int v[maxn]={ 0};
queue< int> Q;
Q.push(s);
v[s] = 1;
while(Q.size())
{
s = Q.front();Q.pop();
if(s == e)
return v[s]- 1;
int t = 1000;
for(i= 0; i< 4; i++)
{
q = Turn(s, i);
for(k= 0; k< 10; k++)
{
j = q+k*t;
if(p[j] == 1 && v[j] == 0)
{
Q.push(j);
v[j] = v[s] + 1;
}
}
t /= 10;
}
}
return - 1;
}
int main()
{
int i, s, e, T;
for(i= 1000; i<maxn; i++)
p[i] = Prime(i);
scanf( " %d ", &T);
while(T--)
{
scanf( " %d%d ", &s, &e);
int ans = BFS(s, e);
if(ans == - 1)
printf( " Impossible\n ");
else
printf( " %d\n ", ans);
}
return 0;
#include< string.h>
#include<math.h>
#include<queue>
using namespace std;
#define maxn 10000
int p[maxn]; // 标记4位数的素数
int Prime( int n)
{
int i, k=sqrt(n);
for(i= 2; i<=k; i++)
if(n % i == 0)
return 0;
return 1;
}
int Turn( int n, int k) // 把n的第k位转换成0
{
char s[ 10]={ 0};
sprintf(s, " %d ", n);
s[k] = ' 0 ';
sscanf(s, " %d ", &n);
return n;
}
int BFS( int s, int e)
{
int i, j, k, q;
int v[maxn]={ 0};
queue< int> Q;
Q.push(s);
v[s] = 1;
while(Q.size())
{
s = Q.front();Q.pop();
if(s == e)
return v[s]- 1;
int t = 1000;
for(i= 0; i< 4; i++)
{
q = Turn(s, i);
for(k= 0; k< 10; k++)
{
j = q+k*t;
if(p[j] == 1 && v[j] == 0)
{
Q.push(j);
v[j] = v[s] + 1;
}
}
t /= 10;
}
}
return - 1;
}
int main()
{
int i, s, e, T;
for(i= 1000; i<maxn; i++)
p[i] = Prime(i);
scanf( " %d ", &T);
while(T--)
{
scanf( " %d%d ", &s, &e);
int ans = BFS(s, e);
if(ans == - 1)
printf( " Impossible\n ");
else
printf( " %d\n ", ans);
}
return 0;
}