In The Sorting Game, you are given a sequence containing a permutation of the integers between 1 and n, inclusive. In one move, you can take any k consecutive elements of the sequence and reverse their order. The goal of the game is to sort the sequence in ascending order. You are given a vector <int> board describing the initial sequence. Return the fewest number of moves necessary to finish the game successfully, or -1 if it's impossible.
Definition
Class:
SortingGame
Method:
fewestMoves
Parameters:
vector <int>, int
Returns:
int
Method signature:
int fewestMoves(vector <int> board, int k)
(be sure your method is public)
Constraints
-
board will contain between 2 and 8 elements, inclusive.
-
Each integer between 1 and the size of board, inclusive, will appear in board exactly once.
-
k will be between 2 and the size of board, inclusive.
Examples
0)
{1,2,3}
3
Returns: 0
The sequence is already sorted, so we don't need any moves.
1)
{3,2,1}
3
Returns: 1
We can reverse the whole sequence with one move here.
2)
{5,4,3,2,1}
2
Returns: 10
This one is more complex.
3)
{3,2,4,1,5}
4
Returns: -1
4)
{7,2,1,6,8,4,3,5}
4
Returns: 7
#include<iostream> #include<stdlib.h> #include<vector> #include<sstream> #include<string> #include<queue> #include<map> #include<stack> #include<math.h> #include<algorithm> usingnamespace std; /**//*BSF algorithm */ // rec to give the change sequence; class SortingGame ...{ public: int fewestMoves(vector <int> board, int k); }; int SortingGame::fewestMoves(vector <int> board, int k) ...{ int i(0); int res(0); stack<int>seq; map<vector<int>,int> path; path[board] =0; queue< vector<int>> Q; Q.push(board); vector<int>u; vector<int> w ; map< vector<int> ,string> rec; string s =""; char c; rec[board] ="0"; while(!Q.empty()) ...{ u = Q.front(); Q.pop(); res = path[u]; for(i =1;i<u.size();i++) ...{ if(u[i]<u[i-1]) break; } if(i == u.size()) ...{ cout<<rec[u]<<endl; return res; } for(i =0;i+k<=u.size();i++) ...{ w = u; s = rec[w]; reverse(w.begin() + i, w.begin() + i + k); c ='0'+i; s += c; if(path.count(w) ==0) ...{ rec[w] = s; path[w] = res+1; Q.push(w); } } } return-1; }