Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3647 | Accepted: 759 |
Description
Input
Output
Sample Input
123456 654321
Sample Output
11
我的BFS超时了,不知道该在哪里剪枝...::>.<::
#include<iostream> #include<cmath> using namespace std; int start,end,queue[10000000],head,rear; char lock[1000000][7]; void push(int i) { queue[rear++%10000000]=i; } int pop() { return queue[head++%10000000]; } int getnum(int n,int th) { th=6-th; while(th--) n/=10; return n%10; } int bfs() { int locate,nownum,step; while(head!=rear) { nownum=pop(); locate=pop(); step=pop(); if(nownum==end) return step; if(locate>1&&!lock[nownum][locate-1]) { lock[nownum][locate-1]=1; push(nownum); push(locate-1); push(step+1); } if(locate<6&&!lock[nownum][locate+1]) { lock[nownum][locate+1]=1; push(nownum); push(locate+1); push(step+1); } //swop 1 if(locate!=1) { int a=getnum(nownum,locate),b=nownum/100000,c=nownum%100000+a*100000-a*(int)pow(10.0,6-locate)+b*(int)pow(10.0,6-locate); if(lock[c][locate]==0) { lock[c][locate]=1; push(c); push(locate); push(step+1); } } //swop 2 if(locate!=6) { int a=getnum(nownum,locate),b=nownum%10,c=nownum-a*(int)pow(10.0,6-locate)+b*(int)pow(10.0,6-locate)-b+a; if(lock[c][locate]==0) { lock[c][locate]=1; push(c); push(locate); push(step+1); } } //swop 3 if(getnum(nownum,locate)!=9) { int a=nownum+(int)pow(10.0,6-locate); if(!lock[a][locate]) { lock[a][locate]=1; push(a); push(locate); push(step+1); } } if(getnum(nownum,locate)!=0) { int a=nownum-(int)pow(10.0,6-locate); if(!lock[a][locate]) { lock[a][locate]=1; push(a); push(locate); push(step+1); } } } } int main() { memset(lock,0,sizeof(lock)); head=rear=0; cin>>start>>end; push(start); push(1); push(0); lock[start][1]=1; cout<<bfs()<<endl; return 0; }