POJ3126 Prime Path

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

题目大意:给两个数四位数m, n, m的位数各个位改变一位0 —— 9使得改变后的数为素数,
问经过多少次变化使其等于n
如:
1033
1733
3733
3739
3779
8779
8179
分析:用字符串存m,n,这样改变各个位较方便

数组开大一点,开始数组开小了,结果就出错了

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<string.h>
#define max(a, b)(a > b ? a : b)
#define min(a, b)(a < b ? a : b)
#define INF 0xffffff
#define N 10010 using namespace std; struct node
{
char s[];
int step;
}; char s1[], s2[], s3[];
bool vis[N]; int prime(int n)
{
int i, k = (int)sqrt(n);
for(i = ; i <= k ; i++)
if(n % i == )
return ;
return ;
} int BFS(char s[])
{
queue<node>Q;
node now, next;
int i, j, h, x = ;
memset(vis, false, sizeof(vis));
memset(s3, , sizeof(s3));
for(i = ; i < ; i++)
x = x * + (s[i] - '');
vis[x] = true;
strcpy(now.s, s);
now.step = ;
Q.push(now);
while(!Q.empty())
{
now = Q.front();
Q.pop();
if(strcmp(now.s, s2) == )
return now.step;
for(i = ; i < ; i++)
{
for(j = ; j < ; j++)
{
if((i == && j == ) || now.s[i] == j + '')
continue;
strcpy(s3, now.s);
now.s[i] = j + '';
x = ;
for(h = ; h < ; h++)
x = x * + (now.s[h] - '');
if(!vis[x] && prime(x) == )
{
vis[x] = true;
next.step = now.step + ;
strcpy(next.s, now.s);
// i = 0;
// j = 0;
Q.push(next);
}
strcpy(now.s, s3);
}
}
}
return -;
} int main()
{
int t;
scanf("%d", &t);
while(t--)
{
scanf("%s%s", s1, s2);
printf("%d\n", BFS(s1));
}
return ;
}
上一篇:(剑指Offer)面试题46:求1+2+3+....+n


下一篇:(转)走进JVM,浅水也能捉鱼