本文共 3363 字,大约阅读时间需要 11 分钟。
Now an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9.
The input file begins with an integer T, indicating the number of test cases.
For each test case, print the minimal steps in one line.
2
1111
简单的广索题。。
1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 using std::cin; 10 using std::cout; 11 using std::endl; 12 using std::swap; 13 using std::sort; 14 using std::map; 15 using std::pair; 16 using std::queue; 17 using std::vector; 18 using std::multimap; 19 #define pb(e) push_back(e) 20 #define sz(c) (int)(c).size() 21 #define mp(a, b) make_pair(a, b) 22 #define all(c) (c).begin(), (c).end() 23 #define iter(c) decltype((c).begin()) 24 #define cls(arr,val) memset(arr,val,sizeof(arr)) 25 #define cpresent(c, e) (find(all(c), (e)) != (c).end()) 26 #define rep(i, n) for (int i = 0; i < (int)(n); i++) 27 #define tr(c, i) for (iter(c) i = (c).begin(); i != (c).end(); ++i) 28 const int N = 10010; 29 typedef unsigned long long ull; 30 bool vis[N]; 31 int start, end; 32 struct Node { 33 int v, s; 34 Node(int i = 0, int j = 0) :v(i), s(j) {} 35 }; 36 inline void calc_1(int *arr, int v) { 37 int i, t, j = 0; 38 do arr[j++] = v % 10; while (v /= 10); 39 for (i = 0, --j; i < j; i++, j--) { 40 t = arr[i]; 41 arr[i] = arr[j]; 42 arr[j] = t; 43 } 44 } 45 inline int calc_2(int *arr) { 46 int sum = 0; 47 rep(i, 4) sum = sum * 10 + arr[i]; 48 return sum; 49 } 50 inline void calc_3(queue &q, int k, int s) { 51 if (!vis[k]) { 52 q.push(Node(k, s + 1)); 53 vis[k] = true; 54 } 55 } 56 int bfs() { 57 int v, k, tmp[10]; 58 cls(vis, false); 59 queue q; 60 q.push(Node(start, 0)); 61 vis[start] = true; 62 while (!q.empty()) { 63 Node t = q.front(); q.pop(); 64 if (t.v == end) return t.s; 65 calc_1(tmp, t.v); 66 rep(i, 4) { 67 v = tmp[i]; 68 if (v + 1 == 10) tmp[i] = 1; 69 else tmp[i] = v + 1; 70 k = calc_2(tmp); 71 calc_3(q, k, t.s); 72 tmp[i] = v; 73 if (v - 1 == 0) tmp[i] = 9; 74 else tmp[i] = v - 1; 75 k = calc_2(tmp); 76 calc_3(q, k, t.s); 77 tmp[i] = v; 78 } 79 rep(i, 3) { 80 calc_1(tmp, t.v); 81 swap(tmp[i], tmp[i + 1]); 82 k = calc_2(tmp); 83 calc_3(q, k, t.s); 84 } 85 } 86 return 0; 87 } 88 int main() { 89 #ifdef LOCAL 90 freopen("in.txt", "r", stdin); 91 freopen("out.txt", "w+", stdout); 92 #endif 93 int t; 94 scanf("%d", &t); 95 while (t--) { 96 scanf("%d %d", &start, &end); 97 printf("%d\n", bfs()); 98 } 99 return 0;100 }
转载于:https://www.cnblogs.com/GadyPu/p/4635111.html