tcbpg

Untitled

Sep 6th, 2011
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <queue>
  5. #include <map>
  6. #include <algorithm>
  7.  
  8. using namespace std;
  9.  
  10. #define forn(i, n) for(int i = 0; i < (int) (n); i++)
  11. #define forsn(i, s, n) for(int i = (s); i < (int) (n); i++)
  12. #define dforn(i, n) for(int i = ((int)(n) -1 ); i >= 0; i--)
  13.  
  14. typedef pair<int, int> pint;
  15.  
  16. map<int, char> D;
  17.  
  18. void decode(int perm, int arr[]){
  19.     forn(i, 10) arr[i] = i;
  20.  
  21.     bool app[10];
  22.     memset(app, 0, sizeof(app));
  23.  
  24.     dforn(i, 9){
  25.         arr[i] = perm % 10;
  26.         app[ arr[i] ] = true;
  27.  
  28.         perm = perm/10;
  29.     }
  30.  
  31.     forn(i, 10) if(!app[i]) arr[9] = i;
  32. }
  33.  
  34. int encode(int arr[]){
  35.     int perm = 0;
  36.     forn(i, 9){
  37.         perm = 10*perm + arr[i];
  38.     }
  39.  
  40.     return perm;
  41. }
  42.  
  43. int flip(int perm, int s, int e){
  44.     int arr[10], arrcp[10]; decode(perm, arr);
  45.     memcpy(arrcp, arr, sizeof(arr));
  46.  
  47.     forsn(i, s, e+1) arr[i] = arrcp[e+s-i];
  48.  
  49.     return encode(arr);
  50. }
  51.  
  52. void calc(){
  53.     queue< pair<int, int> > Q;
  54.  
  55.     int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  56.     do{ D[ encode(arr) ] = -1; }while(next_permutation(arr, arr+10));
  57.  
  58.     D[12345678] = 0;
  59.     Q.push(make_pair(0, 12345678));
  60.  
  61.     while(!Q.empty()){
  62.         pint p = Q.front(); Q.pop();
  63.         int perm = p.second, d = p.first;
  64.  
  65.         forn(i, 10)
  66.             forsn(j, i+1, 10){
  67.                 int next = flip(perm, i, j);
  68.                 if(D[ next ] == -1 && d <= 10){
  69.                     D[ next ] = d+1;
  70.                     Q.push(make_pair(d+1, next));
  71.                 }
  72.             }
  73.     }
  74. }
  75.  
  76. int main(){
  77. #ifdef ACM
  78.     freopen("test.in", "r", stdin);
  79. #endif
  80.  
  81.     char s[16], t[16];
  82.  
  83.     calc();
  84.     while(scanf("%s %s\n", s, t) && strcmp(s, "*")){
  85.         int n = 0, m = 0;
  86.  
  87.         forn(i, 9){
  88.             n = 10*n + (s[i] - 'a');
  89.             m = 10*m + (t[i] - 'a');
  90.         }
  91.  
  92.         int pn = D[ n ], pm = D[ m ];
  93.         printf("%d\n", max(pn, pm)-min(pn, pm));
  94.     }
  95.  
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment