STL

来源:互联网 发布:软件冲突蓝屏怎么办 编辑:程序博客网 时间:2024/05/17 22:11

Problem Statement

 In The Sorting Game, you are given a sequence containing a permutation of the integers between 1 andn, 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:SortingGameMethod:fewestMovesParameters:vector <int>, intReturns:intMethod 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 inboard 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<stdio.h>#include<string.h>#include<algorithm>#include<vector>#include<queue>#include<map>#include<stdlib.h>#include<string>using namespace std;class SortingGame{public:int fewestMoves(vector<int>board, int k){map<vector<int>,int>m;vector<int>res;queue<pair<vector<int>,int> >q;//定义时m[board]=0;q.push(make_pair(board,0));sort(board.begin(),board.end());while(!q.empty()){vector<int>v=q.front().first;int d=q.front().second;q.pop();if(board==v) return d;for(int i=0;i+k<=v.size();i++){vector<int>w=v;reverse(w.begin()+i,w.begin()+i+k);//反转[w.begin()+i,w.begin()+i+k);if(!m.count(w))//w出现的个数{m[w]=d+1;q.push(make_pair(w,d+1));}}}return -1;}};


 

原创粉丝点击