Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15921 | Accepted: 8987 |
Description
1033The 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.
1733
3733
3739
3779
8779
8179
Input
Output
Sample Input
3 1033 8179 1373 8017 1033 1033
Sample Output
6 7 0
分析:一个数字枚举出所有的状态,就是bfs嘛。水题,双向bfs如何实现是个问题。
code:
#include <cstdio> #include <cstring> #include <queue> #include <iostream> using namespace std; typedef long long ll; typedef struct{ int number[4]; int wal; }data; data star,en; int n,m; int is_prim[10005],vis[10005]; int dir[]={1,10,100,1000}; void init() { cin>>n>>m; memset(vis,0,sizeof vis); star.number[0]=n/1000; star.number[1]=n/100%10; star.number[2]=n/10%10; star.number[3]=n%10; en.number[0]=m/1000; en.number[1]=m/100%10; en.number[2]=m/10%10; en.number[3]=m%10; star.wal=0; en.wal=0; } void prim_() { memset(is_prim,0,sizeof is_prim); for(int i=2;i<=9999;i++) { if(is_prim[i]==1) continue; for(int j=i*2;j<=9999;j+=i) { is_prim[j]=1; } } } void bfs() { queue <data> qf; queue <data> qb; vis[n]=1; qf.push(star); qb.push(en); while(qf.size()) { data nos,noe; nos=qf.front(); noe=qb.front(); int stemp=0,etemp=0; for(int i=0;i<4;i++) { stemp=stemp*10+nos.number[i]; etemp=etemp*10+noe.number[i]; } qf.pop(); qb.pop(); if(stemp==m) { cout<<nos.wal<<endl; return ; } //r printf("%d %d\n",stemp,etemp); data ne1,ne2; ne1=nos,ne2=noe; ne1.wal=nos.wal+1; ne2.wal=noe.wal+1; for(int i=0;i<4;i++) { for(int j=0;j<=9;j++) { ne1=nos; ne2=noe; if(i==0&&j==0) continue; ne1.number[i]=j; ne2.number[i]=j; stemp=0,etemp=0; for(int q=0;q<4;q++) { stemp=stemp*10+ne1.number[q]; etemp=etemp*10+ne2.number[q]; } if(1000<=stemp&&etemp<=9999) { if(!vis[stemp]&&!is_prim[stemp]) { vis[stemp]=1; ne1.wal=nos.wal+1; qf.push(ne1); } } if(1000<=etemp&&etemp<=9999) { if(!vis[etemp]&&is_prim[etemp]) { vis[etemp]=1; ne2.wal=noe.wal+1; qb.push(ne2); } } } } } } int main(void) { prim_(); int t; cin>>t; while(t--) { init(); bfs(); } }