hdu 1973 bfs+素数判断

题意:给出两个四位数,现要改变第一个数中的个,十,百,千位当中的一个数
使它最终变成第二个数,要求这过程中形成的数是素数,问最少的步骤
题解:素数筛选+bfs
Sample Input
3
1033 8179
1373 8017
1033 1033
Sample Output
6
7
0

 

注意第一位不能变成0即可

 1 #include<cstdio>

 2 #include<iostream>

 3 #include<algorithm>

 4 #include<cstring>

 5 #include<cmath>

 6 #include<queue>

 7 #include<map>

 8 using namespace std;

 9 #define MOD 1000000007

10 const int INF=0x3f3f3f3f;

11 const double eps=1e-5;

12 #define cl(a) memset(a,0,sizeof(a))

13 #define ts printf("*****\n");

14 const int MAXN=1005;

15 int n,m,tt,time;

16 struct node

17 {

18     char s[5];

19     int t;

20 }st,ed;

21 

22 bool prime[10005];

23 bool vis[10005];

24 void isprime() {//素数筛选

25     int i,j;

26     for(i=2; i<10005; i++)prime[i]=1;

27     prime[0]=0,prime[1]=0;

28 

29 

30     for(i=2; i<10005; i++) {

31         if(prime[i]) {

32             for(j=2*i; j<10005; j+=i) {

33                 prime[j]=0;

34             }

35         }

36     }

37 }

38 void bfs()

39 {

40     node now,next;

41     queue<node> q;

42     q.push(st);

43     int x=0;

44     for(int i=0;i<4;i++)    x=x*10+(st.s[i]-'0');

45     vis[x]=1;

46     while(!q.empty())

47     {

48         now=q.front();

49         q.pop();

50         if(strcmp(ed.s,now.s)==0)

51         {

52             printf("%d\n",now.t);

53         }

54         for(int i=0;i<4;i++)    //4位

55         {

56             strcpy(next.s,now.s);

57             next.t=now.t+1;

58             for(int j=0;j<=9;j++)   //尝试在每位填数字

59             {

60                 if(i==0&&j==0)  continue;

61                 if(next.s[i]-'0'==j)    continue;   //原来就有的就不用填了

62                 next.s[i]=j+'0';

63                 x=0;

64                 for(int w=0;w<4;w++)    x=x*10+(next.s[w]-'0');

65                 if(prime[x]&&!vis[x])

66                 {

67                     vis[x]=1;

68                     q.push(next);

69                 }

70             }

71         }

72     }

73 

74 }

75 int main()

76 {

77     int i,j,k;

78     #ifndef ONLINE_JUDGE

79     freopen("1.in","r",stdin);

80     #endif

81     isprime();

82     scanf("%d",&tt);

83     while(tt--)

84     {

85         scanf("%s%s",st.s,ed.s);

86         st.t=0;

87         cl(vis);

88         bfs();

89     }

90 }

 

你可能感兴趣的:(HDU)