Advertisement
Guest User

Aideen's Code for Kahu's 9402

a guest
Mar 23rd, 2015
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. //Author: aideen.org
  2. //Date: 3/23/2015
  3.  
  4. #include <iostream>
  5. #include <vector>
  6. #include <map>
  7. #include <unordered_map>
  8. using namespace std;
  9.  
  10. int N;
  11. typedef vector<char> V;
  12.  
  13. const int H = 3281533; //668273;
  14.  
  15. struct hashF {
  16.   size_t operator()(const V& x) const {
  17.     int ret = 0;
  18.     for (int i=0; i<N; i++) ret = (ret * 10 + x[i]);
  19.     return ret % H;
  20.   }
  21. };
  22.  
  23. struct eqV
  24. {
  25.   bool operator()(const V &v1, const V &v2) const
  26.   {
  27.     return v1 == v2;
  28.   }
  29. };
  30.  
  31. unordered_map<V, pair<char, V>, hashF, eqV > mhash;
  32.  
  33. V start, goal;
  34.  
  35. #define showrow(r) for(int xxx=0;xxx<r.size();xxx++)cerr<<1+r[xxx]<<",";cerr<<endl;
  36.  
  37. int V2int(V v) {
  38.   int ret = 0;
  39.   for (int i=0; i<N; i++) {
  40.     ret = ret * 10 + v[i];
  41.   }
  42.   return ret;
  43. }
  44.  
  45. void BFS(const V &start) {
  46.   cerr << "starting..." << endl;
  47.   vector<V> q;
  48.   q.push_back(start);
  49.   mhash[start] = make_pair(1, V(0));
  50.  
  51.   V b;
  52.   char x;
  53.   for (int ql = 0; ql<q.size(); ql++) {
  54.     V current = q[ql];
  55.     for (char i=0; i<N; i++) {
  56.       for (char j=i+1; j<=N; j++) { // [i, i+1, ..., j) is cut and moved forward to after [k]
  57.     for (char k=j; k<N; k++) {
  58.       b = current;
  59.       for (x=j; x<=k; x++)  b[i + (x - j)] = current[x];
  60.       for (x=i; x<j; x++)   b[i + (k - j + 1) + (x - i)] = current[x];
  61.  
  62.       if (mhash[b].first != 0) { continue; }
  63.       q.push_back(b);
  64.       mhash[b] = make_pair(mhash[current].first + 1, current);
  65.  
  66.       if (b == goal) { 
  67.         cerr << "yeaaah! after " << q.size() << " nodes " << endl;
  68.         return;
  69.       }
  70.     }
  71.       }
  72.     }
  73.   }
  74. }
  75.  
  76. int main(int argc, char **argv) {
  77.   N = atoi(argv[1]);
  78.  
  79.   for (int i=0; i<N; i++) goal.push_back(i), start.push_back(N-1-i);
  80.  
  81.   BFS(start);
  82.  
  83.   cout << int(mhash[goal].first-1) << endl;
  84.  
  85.   for (V cur = goal; cur.size(); cur = mhash[cur].second) {
  86.     showrow(cur);
  87.   }
  88.  
  89.   return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement