POJ -3126-Prime Path
2012-08-10 12:39
274 查看
POJ -3126-Prime Path
http://poj.org/problem?id=3126
素数打表加BFS
http://poj.org/problem?id=3126
素数打表加BFS
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<queue> using namespace std; #define N 10005 int prime[10005]; int visit ; struct node { int x; int step; }; void init() { int i,j; memset(prime,0,sizeof(prime)); for(i=3;i<=100;i+=2) if(prime[i]==0) { for(j=i*i;j<N;j+=2*i) prime[j]=1; } } void bfs(int a,int b) { int i,j; int a1,b1,c1,d1,num; node st,ed; queue<node>q; st.x=a; st.step=0; memset(visit,0,sizeof(visit)); visit[a]=1; q.push(st); while(!q.empty()) { st=q.front(); q.pop(); if(st.x==b) { printf("%d\n",st.step); return; } for(i=0;i<4;i++) { for(j=0;j<10;j++) //将第i位的数字变为j { if(i==0&&j==0) //第一位数字不能变为0 continue; a1=st.x/1000; b1=(st.x/100)%10; c1=(st.x/10)%10; d1=st.x%10; if(i==0) num=j*1000+b1*100+c1*10+d1; else if(i==1) num=a1*1000+j*100+c1*10+d1; else if(i==2) num=a1*1000+b1*100+j*10+d1; else num=a1*1000+b1*100+c1*10+j; if(num!=st.x&&!visit[num]&&num%2==1&&!prime[num]) { ed.x=num; visit[num]=1; ed.step=st.step+1; if(num==b) { printf("%d\n",ed.step); return; } q.push(ed); } } } } printf("Impossible\n"); return; } int main() { int t,a,b; init(); scanf("%d",&t); while(t--) { scanf("%d%d",&a,&b); bfs(a,b); } return 0; }
相关文章推荐
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126:Prime Path
- POJ-3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126:Prime Path
- POJ 3126 Prime Path
- [bfs]poj 3126 Prime Path
- POJ 3126 Prime Path
- POJ - 3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- POJ-3126-Prime Path
- POJ3126——Prime Path
- poj 3126 -- Prime Path
- poj 3126 Prime Path