zoj 2416 Open the Lock(BFS~)

好吧,这道题,我真的卡了好久,为什么呢?没好好读题!!!

 

我了个去!!!

 

本来以为是每次可以变换多个位的 = =。。。结果不是 = =。。

 

以至于我开的数组都没用上 = =。。

 

后来一直没看到那句,不,是没理解,可以交换相邻位 = =。。。一直不对 = =。。。

 

啥破毛病 = =。。。以后要专心看题,专心呐!!!

 

现在代码中注释都用英语写,没其他特殊目的,就是想锻炼英语。。。

 

这次交完发现居然提交数和AC数都很和谐,放图~

zoj 2416 Open the Lock(BFS~)_第1张图片

 

 

#include <stdio.h> #include <stdlib.h> #include <iostream> #include <memory.h> #include <queue> using namespace std; queue <int> Q; int main(void) { int ncases; cin >> ncases; int a,b,y[10],p[10]; int flag[10000],hash[10000]; while( ncases-- ) { memset(flag,0,sizeof(flag)); memset(hash,0,sizeof(hash)); while(!Q.empty()) // Clean queue. Q.pop(); scanf("%d%d",&a,&b); Q.push(a); hash[a] = 1; while( !Q.empty() ) { int x = Q.front(); int temp = x; Q.pop(); int sum; for(int i=0; i<4; i++) // Save the digits of the num. { p[i] = x%10; x /= 10; } for(int i=0; i<3; i++) { memcpy(y,p,sizeof(p)); // To guarantee the y array is the previous one. if( y[i] == y[i+1] ) // If you forget this, you will add repeatedly. continue; swap(y[i],y[i+1]); sum = y[0] + y[1]*10 + y[2]*100 + y[3]*1000; if( !hash[sum] ) // If you didn't use this array to flag, you will compute repeatedly. { flag[sum] = flag[temp] + 1; if( sum == b ) goto end; // = =. My first , use goto .It is easy and convenience to use. Q.push(sum); hash[sum] = 1; } } for(int i=0; i<4; i++) // Add 1. { memcpy(y,p,sizeof(p)); y[i]--; if( y[i] == 0 ) y[i] = 9; sum = y[0] + y[1]*10 + y[2]*100 + y[3]*1000; if( !hash[sum] ) { flag[sum] = flag[temp] + 1; if( sum == b ) goto end; Q.push(sum); hash[sum] = 1; } } for(int i=0; i<4; i++) // Minus 1. { memcpy(y,p,sizeof(p)); y[i]++; if( y[i] == 10 ) y[i] = 1; sum = y[0] + y[1]*10 + y[2]*100 + y[3]*1000; if( !hash[sum] ) { flag[sum] = flag[temp] + 1; if( sum == b ) goto end; Q.push(sum); hash[sum] = 1; } } } end: // Goto end. cout << flag[b] << endl; } return 0; }

你可能感兴趣的:(zoj 2416 Open the Lock(BFS~))