Eight digital problems and a * algorithm

Source: Internet
Author: User
Tags constructor extend numeric relative
Eight digital issues

I. Eight digital issues

Eight digital problems are also called nine problems. On the 3x3 chessboard, there are eight pieces, each of which is marked with a number 1 to 8, and the numbers on each piece are different. There is also a space on the board, and a piece adjacent to the space can be moved to a space. The problem to be solved is to give an initial state and a target state, and to find a moving step with the fewest steps of moving pieces from the initial transition to the target State.
A state of the so-called problem is a pendulum on a chess board. When the pawn moves, the state changes. The problem of solving eight digital problems is actually to find out a series of intermediate transition states from the initial state to the target State.
Eight digital problems generally use the search method to solve.
Search method has breadth-first search method, Depth-first search method, A * algorithm, etc. Here we compare the effects of different search methods by solving eight digital problems in different ways.

two. Search algorithm base class
1. Eight status indication of a digital problem
The eight-digit problem is a state of eight numbers on the board of a method. Each piece is represented by the number indicated on it, and a space is represented by 0, so that a state of a piece on the board can be stored in a one-dimensional array p[9], in order from the upper left corner, from left to right, from top to bottom. You can also use a two-dimensional array to store it.
2. Junction points
In the search algorithm, the state of the problem is described with a node. Node in addition to the description of the state of the array p[9], there is a parent node pointer last, it records the current node's parent node number, if a node V is from the node U through the state changes, the node U is the node v parent node, the last record of Node V is the node U number. After reaching the target node, the search path can be found by last.
3. Structure of the class
In C + +, classes are used to represent nodes, and classes encapsulate data operations related to nodes.
Different search algorithms have a certain commonality, but also have their own personality, so here will be different search algorithm common data and functions encapsulated in a base class, and then through the inheritance of the implementation of different search algorithms.
4. Node expansion rules
Search is to extend known nodes according to certain rules until the target node is found or all nodes cannot be expanded.
The expansion of the eight-digit problem should obey the moving rules of the chess pieces. According to the rules of moving pieces, each time you can move a piece with a space adjacent to the space, can actually be considered as a space for the opposite movement. The direction of the space movement can be right, bottom, left, and above, of course, cannot move out of the boundary.
The position of the pawn, which is the subscript of the array element that holds the state. When the space moves, its position changes, when the space is not shifted to the right, down, left, and up, the new position is the original position plus 1, 3,-1,-3, if the space is left to right, down, left and up, respectively, 0, 1, 2, 3, and 3, 3, 1, 1 in the static array d[4], The space position is represented by SPAC, and then the space moves to direction I, and its position changes to spac+d[i].
The change in state resulting from the movement of the space is reflected in the array p[], the number of the new position at 0 and the 0 swap position.
5. Eight base class for digital issues

The base class of the eight-digit problem and its member functions are implemented as follows:
#define NUM 9 class Teight {Public:teight () {} teight (char *fname);
virtual void Search () = 0;
	Protected:int P[num];
	int Last,spac;
	static int q[num],d[],total;
	void Printf ();
	BOOL operator== (const teight &t);
BOOL Extend (int i);
};
int Teight::q[num];
int teight::d []={1,3,-1,-3};

int teight::total=0;
	Teight::teight (char *fname) {ifstream fin;
	Fin.open (Fname,ios::in | ios::nocreate); if (!fin) {cout<< "Cannot Open data file!"
		<<endl;
	Return
	} int i;
	for (i=0;i<num;) fin>>p[i++];
	fin>>spac;
	for (i=0;i<num;) fin>>q[i++];
	Fin.close ();
	Last=-1;
total=0;
	} void Teight::P rintf () {ofstream fout;
	Fout.open ("Eight_result.txt", Ios::ate|ios::app);
	fout<<total++<< "T";
	for (int i=0;i<num;) fout<< "" <<p[i++];
	fout<<endl;
Fout.close ();
	} bool teight::operator== (const teight &t) {for (int i=0;i<num;) if (t.p[i]!=p[i++]) return 0;
return 1; } bool Teight::extend (int i) {if (i==0 &&spac%3==2 | | I==1 && Spac>5 | | i==2 && spac%3==0 | |
	I==3 && spac<3) return 0;
	int Temp=spac;
	Spac+=d[i];
	P[TEMP]=P[SPAC];
	p[spac]=0;
return 1; }
Structure of the data file:
Altogether three lines, the first line is a space separated by nine digit 0~8, this is the initial state. The second line is the position of a number, a space (number 0), and the third line is a nine digit 0~8 separated by a space, which is the target State.

three. Linear table
Search method in the search process, you need to use a queue to store the intermediate nodes of the search, in order to find the target node, you can find the path from the initial node to the target node, you need to keep all the searched nodes. On the other hand, in different search methods of different problems and even the same problem, the number of nodes that need to be stored varies greatly, so the chain linear table is used as the storage structure, and the linear table is designed into a class template form for adapting to different problems.
Template<class type> class TList;
  Linear table Pre-View definition Template<class type> class Tnode//Linear table node class template {friend class tlist<type>;
Public:tnode () {} tnode (const type& DAT);
       private:tnode<type>* Next;
Type Data;

}; Template<class type> class TList {public:tlist () {last=first=0;   length=0;}   constructor int Getlen () Const{return Length;}           A member function that returns the linear table length int Append (const type& T);       A member function that joins the node int Insert (const type& t,int k) from the end of the table;                         member function, insert node Type GetData (int i); member function, return node data member void SetData (const type& t,int k);             member function, set node data member Private:tnode<type> *first,*last;                                         data member, linear table header, tail pointer int Length;

data member, linear table length};
       Template<class type> int tlist<type>::append (const type& T) {Insert (t,length);
return 1; } Template<class Type> int Tlist<type>::insert (const type& t,int k) {tnode<type> *p=new tnode<type>;
       p->data=t;
                     if (first) {if (k<=0) {p->next=first;
              first=p;   
                     } if (k>length-1) {last->next=p;
                     last=last->next;
              last->next=0;
              } if (k>0 && k<length) {k--;
              Tnode<type> *q=first;
              while (k-->0) q=q->next;
              p->next=q->next;
           q->next=p;
              }} else {first=last=p;
       first->next=last->next=0;
       } length++;
return 1;
       } template<class type> Type tlist<type>::getdata (int k) {tnode<type> *p=first; while (k-->0) p=p->next;
Return p->data; } template<class type> void Tlist<type>::setdata (const type& t,int k) {tnode<type> *p=First
       ;
       while (k-->0) p=p->next;
p->data=t; }
Linear tables are stored separately as header files.

four. Breadth-First Search method
In the search method, the breadth-first search method is the first choice to find the shortest path.
1. Basic steps of breadth-first search algorithm
1) Set up a queue, queue the initial node, and set the header and tail pointers.
2) Take out the nodes of the queue head (pointed by the head pointer) to expand it, extend the sub-nodes from it, and join the queues in the order of expansion.
3) If the expanded new node repeats with the node in the queue, discard the new node and skip to step sixth.
4) If the expanded new node and the node in the queue are not duplicated, the parent node is recorded and queued to update the queue tail pointer.
5) If the expanded node is the target node, the output path, the program ends. Otherwise, proceed to the next step.
6) If the node of the queue header can also be extended, return to the second step directly. Otherwise, point the queue head pointer to the next node, and then return to the second step.
2. Output of the search path
After you have searched for a target node, you need to output the path of the search. Each node has a data field last, it records the parent node of the settlement point, so when the search path is output, it is from the target node Q, according to find its parent node, and then according to the last node to find its parent node, ..., and finally find the initial node. The path to the search is the path from the initial node to the target node in the opposite direction.
3. Breadth-First search method structure of TBFS class
Breadth-First search method The TBFs class is a subclass of the Teight class. The structure and member functions of their classes are implemented as follows:
class tbfs:public teight {public:tbfs () {} tbfs (char *fname): Teight (fname) {} virtual void Search (); p
	Rivate:void printl (tlist<tbfs> &l);
	int Repeat (tlist<tbfs> &l);
int Find ();

};
	void TBFs::P rintl (tlist<tbfs> &l) {TBFs t=*this;
	if (t.last==-1) return;
		else {t=l.getdata (t.last);
		T.printl (L);
	T.printf ();
	}} int Tbfs::repeat (tlist<tbfs> &l) {int N=l.getlen ();
	int i;
	for (i=0;i<n;i++) if (L.getdata (i) ==*this) break;
return i;
	} int Tbfs::find () {for (int i=0;i<num;) if (p[i]!=q[i++]) return 0;
return 1;
	} void Tbfs::search () {TBFS t=*this;
	Tlist<tbfs> L;
	L.append (T);
	int head=0,tail=0;
			while (Head<=tail) {for (int i=0;i<4;i++) {t=l.getdata (head);
				if (T.extend (i) && t.repeat (L) >tail) {t.last=head;
				L.append (T);
			tail++;
				} if (T.find ()) {t.printl (L);
				T.printf ();
			Return
	}} head++; }
}
4. Disadvantages of breadth-first search method
The breadth-first search method is always guaranteed to search the shortest path, that is, to move the least number of steps in the case of the solution. But the biggest problem with the breadth-first search method is that the number of nodes in the search is too large, because in the breadth-first search, each potentially expanding node is the object of the search. As nodes increase in depth on the search tree, the number of nodes in the search grows rapidly and expands exponentially, so that the amount of storage space required and the time it takes to search can grow exponentially.

Five. Bidirectional breadth-First search method
1. Bidirectional breadth-First search method
Eight digital problems are reversible, that is, if you can extend from a state a State B, then the same can be extended from State B, the State A, the problem can be from the initial state, search for the target state, but also from the target State, search the initial state. If the two-way breadth-first search method is adopted for this kind of problem, the time of searching can be greatly saved.
The so-called two-way breadth-first search method, is at the same time from the initial state and target State, the use of breadth-first search strategy, to the other side search, if the problem exists, then the two-direction search will meet halfway, that is, search for the same node. A search path from the initial node to the target node can be obtained by connecting the search paths in two directions.
2. Bidirectional breadth-First search algorithm
The basic steps of the bidirectional breadth-first search algorithm are as follows:
1) Establish two queues, one for the forward lookup, and the other for the reverse search queue. Put the initial node in the forward queue, place the target node in the reverse queue, and set the two-queue header and tail pointers.
2) Extend the node of the queue header (the head pointer) from the forward queue.
3) If the expanded new node repeats with the node in the queue, discard the new node and skip to step sixth.
4) If the expanded new node and the node in the queue are not duplicated, the parent node is recorded and queued to update the queue tail pointer.
5) Check whether the expanded node is in another direction of the queue, if it is a two-direction search encounters, display the search path, the program ends. Otherwise, proceed to the next step.
6) If the node of the queue header can also be extended, return to the second step directly. Otherwise, point the queue head pointer to the next node, and then to the queue that the other party is searching for, follow the same steps as the second step.
3. Advantages of bidirectional breadth-first search method
When searching by breadth-first search method, nodes expand continuously, and the greater the depth, the more nodes. If you search from two directions to the other side, you will meet somewhere in the middle of the path, so that the depth of the search is not very large, the number of nodes searched is much less, the search time will save a lot.
Theoretically, if each node has an expandable sub-node number of m, the search tree of breadth-first search is an M-fork tree, i.e. each node is branched by M. According to the full M-fork tree, if the target node is on the nth level, breadth-first search must extend all nodes of the n-1 layer on the search tree, with the expanded node number m (mn-1)/(m-1). For bi-directional breadth-first search, if the two-direction search generates the same sub-node in layer I, the forward search extension has a node number of M (mi-1)/(m-1), a reverse lookup extension of M (mn-i-1)/(m-1), a total of M (mi+mn-i-1) for the search node ( M-1) (where n is the optimal solution path length, i= (m+1) Div 2,). Set N is even (n=2*i), breadth-first bidirectional search extension node is about breadth-first search of 2/(mi/2+1) *100%, relative reduction (mi/2-1)/(mi/2+1) *100%.
4. Determine the search encounters in two directions
In the bidirectional breadth-first search method, how to judge the two-direction search encounters. As long as we are generating the node, we can determine whether the node appears in the opposite direction of the search tree, that is, in a direction search to expand a new node, if it and another direction has been expanded out of the node to repeat, also find understanding.
5. TDBFS class structure of bidirectional breadth-first search method
The Tdbfs of the bidirectional breadth-first search method is similar to the breadth-first search method, and also the subclass of the Teight class, and the implementation of the class structure and its member functions are as follows:
Class Tdbfs:public Teight {Public:tdbfs () {} tdbfs (char *fname): Teight (fname) {} virtual void Search (); private:void
	PRINTP (tlist<tdbfs> &l);
	void Printb (tlist<tdbfs> &l);  
int Repeat (tlist<tdbfs> &l);

};
	void Tdbfs::P rintp (tlist<tdbfs> &l) {Tdbfs t=*this;
	if (t.last==-1) return;
		else {t=l.getdata (t.last);
		T.PRINTP (L);
	T.printf ();
	}} void Tdbfs::P rintb (tlist<tdbfs> &l) {Tdbfs t=*this;
		while (t.last>-1) {t=l.getdata (t.last);
	T.printf ();
	}} int Tdbfs::repeat (tlist<tdbfs> &l) {int N=l.getlen ();
	int i;
	for (i=0;i<n;) if (L.getdata (i++) ==*this) break;
return i;
	} void Tdbfs::search () {TDBFS t1=*this;
	Tdbfs T2;
		for (int i=0;i<num;i++) {t2.p[i]=q[i];
	if (q[i]==0) t2.spac=i;
	} t2.last=-1;
	Tlist<tdbfs> L1,l2; L1.
	Append (T1); L2.
	Append (T2);
	int head1=0,tail1=0,head2=0,tail2=0; while (Head1<=tail1 | | head2<=tail2) {for (int i=0;i<4;i++) {t1=l1.GetData (HEAD1); if (T1. Extend (i) && T1.
				Repeat (L1) >tail1) {t1.last=head1; L1.
				Append (T1);
			tail1++; } int m=t1.
			Repeat (L2); if (M&LT;TAIL2) {T1.
				PRINTP (L1); T1.
				Printf (); T2=l2.
				GetData (m); T2.
				PRINTB (L2);
			Return
		}} head1++; for (i=0;i<4;i++) {t2=l2.
			GetData (HEAD2); if (T2. Extend (i) && T2.
				Repeat (L2) >tail2) {t2.last=head2; L2.
				Append (T2);
			tail2++; } int m=t2.
			Repeat (L1); if (M&LT;TAIL1) {t1=l1.
				GetData (m); T1.
				PRINTB (L1); T1.
				Printf (); T2.

				PRINTP (L2);
			Return
	}} head2++; }
}

Six. A * algorithm
1. Heuristic Search
Breadth-First search and two-way breadth-first search are blind search, which is a very appropriate algorithm in the case of small state space, but when the state space is very large, their efficiency is too low, often in search of a large number of unrelated state nodes to meet the answer, or even can not touch the answer.
Searching is a tentative search process, in order to reduce the blindness of the search and increase the accuracy of the test, it is necessary to use heuristic search. The so-called heuristic search is in the search for the location of each search to evaluate, choose the best, may be easy to reach the target location, and then search from this position forward, so that the search can omit a large number of unrelated nodes, improve efficiency.
2.a* algorithm
A * algorithm is a common heuristic search algorithm.
In a * algorithm, the location of a node is evaluated using a valuation function. The estimate function of a * algorithm can be expressed as:
F ' (n) = G ' (n) + h ' (n)
Here, F ' (n) is the valuation function, and G ' (n) is the shortest Path value (also known as the minimum or minimum cost) from the starting point to the end point, and H ' (n) is the heuristic value for the shortest path through N to the target. Since this f ' (n) is actually not known in advance, the following valuation function is actually used:
F (n) = g (n) + H (n)
where g (n) is the actual cost from the initial junction to the node n, h (n) is the estimated cost of the best path from node n to the target node. Here the main is H (N) embodies the heuristic information of the search, because g (n) is known. Use f (n) as an approximation of f ' (n), i.e. g (n) instead of G ' (n), h (n) instead of H ' (n). This must satisfy two conditions: (1) g (n) >=g ' (n) (most of the cases are satisfied, can be considered), and F must remain monotonically increasing. (2) H must be less than or equal to the actual minimum consumed h (n) <=h ' (n) to reach the target node from the current node. 2nd of particular importance. It can be proved that the shortest path can be found by applying such a valuation function.
Steps for the 3.a* algorithm
A * algorithm is basically the same as the breadth first algorithm, but after extending a node, it calculates its valuation function and treats the extended node sort according to the value function, thus ensuring that the node of each expansion is the least node of the valued function.
The steps for a * algorithm are as follows:
1) Set up a queue, calculate the value function f of the initial node, and queue the initial node, set the head and tail pointers.
2) Remove the node of the queue header (referred to by the queue head pointer), if the node is the target node, the output path, the program ends. Otherwise, the nodes are expanded.
3) Check to see if the new node is expanded to duplicate the node in the queue. If the node that cannot be expanded is repeated (before the queue head pointer), it is discarded, and if the new node repeats with the node to be expanded (after the queue header pointer), the size of the G in the estimate function of the two nodes is compared, and the nodes with the smaller G values are preserved. Skip to step fifth.
4) If the expanded new node and the node in the queue are not duplicated, then it is inserted into the head node in the queue after its value function f size to expand the node to the appropriate location, so that they in order from small to large, and finally update the queue tail pointer.
5) If the node of the queue header can also be extended, return to the second step directly. Otherwise, point the queue head pointer to the next node, and then return to the second step.
4. Eight evaluation function of a * algorithm for digital problems
In the valuation function, the main is to calculate h, for different problems, H has different meanings. So what is the implication of H in the eight-digit question? A state of eight digital problems is actually a permutation of the digital 0~8, with an array of p[9] to store it, and the subscript of each element in the array is the position of that number in the arrangement. For example, in one state, p[3]=7, the position of the number 7 is 3. If the position of the target status number 3 is 8, then the offset distance of the number 7 to the target State is 3, because it moves 3 steps before returning to the position of the target State.
Eight digital problems, each number can have 9 different positions, therefore, in any state of each number and the target state of the same number of the relative distance between the 9*9 species, you can first calculate these relative distances, with a matrix storage, so as long as you know the position of the same number of two States, You can find out their relative distances, that is, the offset distance of the number:
0 1 2 3 4 5 6 7 8
0 0 1 2 1 2 3 2 3 4
1 1 0 1 2 1 2 3 2 3
2 2 1 0 3 2 1 4 3 2
3 1 2 3 0 1 2 1 2 3
4 2 1 2 1 0 1 2 1 2
5 3 2 1 2 1 0 3 2 1
6 2 3 4 1 2 3 0 1 2
7 3 2 3 2 1 2 1 0 1
8 4 3 2 3 2 1 2 1 0
For example, in one State where the position of the number 8 is 3 and the position in the other state is 7, then 7 is found from the 3 row 2 column of the Matrix, which is the offset distance of 8 in both states.
The h in the valuation function is the sum of all the digital offset distances.
Obviously, to calculate the offset distance of the same number in two different states, you need to know the position of the number in each state, which is to be scanned with the array p[9]. As the status changes, the positions of the numbers also change, so each time the H is computed, the array is scanned to determine the position of each number in the array. To simplify the calculations, here An array is used to store the positions of each number in the state and to change as the state changes so that it does not have to scan the state array each time H is computed.
For example, in a state where the position of the number 5 is 8, if the location is stored with an array of r[9], then there is r[5]=8.
Now using the array r[9] to store the numeric position of the current state, and using s[9] to store the numeric position of the target State, the current state number I offset the target state from the value of the R[i row s[i] column in the Matrix.
Class structure of 5.a* algorithm
The class declaration of the * algorithm is as follows:
Class Tastar:public Teight {Public:tastar () {}//constructor Tastar (char *fname1,char *fname2);               With parametric constructor virtual void Search ();                               A * search method Private:int f,g,h;                              Valuation function int R[num];                       Auxiliary array for each numeric position in the storage state static int s[num];        A secondary array that stores the position of each digit in the target State, static int e[];////////////Store the auxiliary array of each digit relative distance void Printl (tlist<tastar> L);                        member function, output search path int expend (int i);                             member functions, A * algorithm's state extension function int calcuf ();  The member function calculates the valuation function void Sort (tlist<tastar>& l,int k);       member function to insert the new extension node into the order of F to expand the node queue int Repeat (tlist<tastar> &l) from small to large;

member function, check whether the node is repeated};

int Tastar::s[num],tastar::e[num*num];
	Tastar::tastar (char *fname1,char *fname2): Teight (fname1) {for (int i=0;i<num;)   {r[p[i]]=i; Store the initial state of each digit position s[q[i]]=i++;                     
	Stores the target state where each digit is located} ifstream fin; Fin.open (fname2,ios::in | ios::nocreate)///Open Data file if (!fin) {cout<< "Cannot Open data file!"
		<<endl;
	Return
	} for (i=0;i<num*num;i++)//read in each number relative distance value fin>>e[i];
	Fin.close ();       f=g=h=0;
	Valuation function Initial value} void Tastar::P rintl (tlist<tastar> L) {Tastar t=*this;
	if (t.last==-1) return;
		else {t=l.getdata (t.last);
		T.printl (L);
	T.printf ();   }} int Tastar::expend (int i) {if (Extend (i))//node extensible {int temp=r[p[r[0]];
		Change the position of the number after changing the position of the change after storage r[p[r[0]]]=r[0];
		R[0]=temp;
	return 1;
} return 0;
	} int Tastar::calcuf () {h=0;
	for (int i=0;i<num;i++)//h h+=e[num*r[i]+s[i] [calculates the valuation function];                                     
return ++g+h;
	} void Tastar::sort (tlist<tastar>& l,int k) {int n=l.getlen ();
		for (int i=k+1;i<n;i++) {Tastar t=l.getdata (i);
	if (THIS-&GT;F&LT;=T.F) break;
} l.insert (*this,i);
	} int tastar::repeat (tlist<tastar> &l) {int N=l.getlen ();
for (int i=0;i<n;i++) if (L.getdata (i) ==*this)			Break
return i;              } void Tastar::search () {Tastar t=*this;               Initial node t.f=t.calcuf ();           The evaluation function of the initial node tlist<tastar> L;                 Establish queue l.append (T);           The initial node is enqueued int head=0,tail=0; The queue header and the tail pointer while (HEAD&LT;=TAIL)//queue is not empty then the loop {for (int i=0;i<4;i++)//space may move in the direction {T=l.getdata (   Head);    Go to queue Header node if (t.h==0)//is the target node {t.printl (L);//Output search path t.printf ();        Output target status return;               End} if (T.expend (i))//if node extensible {int k=t.repeat (L);//Returns the ordinal if (K 

Seven. Test Procedures

Test for A * algorithm:

int main ()
{
    Tastar aStar ("Eight.txt", "Eight_dis.txt");
    Astar.search ();
    return 0;
}
Data in the Eight.txt file (initial state and target State):
Altogether three lines, the first line is a space separated by nine digit 0~8, this is the initial state. The second line is the position of a number, a space (number 0), and the third line is a nine digit 0~8 separated by a space, which is the target State.

8 3 5 1 2 7 4 6 0
8
1 2 3 4 5 6 7 8 0

Data in Eight_dis.txt (estimated function usage):
0 1 2 1 2 3 2 3 4
1 0 1 2 1 2 3 2 3
2 1 0 3 2 1 4 3 2
1 2 3 0 1 2 1 2 3
2 1 2 1 0 1 2 1 2
3 2 1 2 1 0 3 2 1
2 3 4 1 2 3 0 1 2
3 2 3 2 1 2 1 0 1

4 3 2 3 2 1 2 1 0


eight. Algorithm Run results
The 1.BFS algorithm can only be applied to situations where there are fewer steps to reach the target node, and if the number of steps exceeds 15 steps, the run time is too long and actually no longer works.
2. For the same solvable state of random generation, the BFS algorithm is the slowest, the DBFS algorithm is slower, and a * algorithm is faster. However, within 15 steps, the DBFS algorithm and A * algorithm time difference is not small, more than 15 steps, with the number of steps, the advantage of a * algorithm is gradually obvious, a * algorithm is 5 times times faster than the DBFS algorithm, and increases with the number of steps. By more than 25 steps, the DBFS also loses value because of the long running time.
3. In general, the number of moving steps of the solution increased by 1, the program run time will increase by more than 5 times times. Due to the characteristics of the eight digital problems, the number of nodes that need to be checked increases exponentially with the steps, that is, using a * algorithm, it is difficult to solve the problem of moving steps more.

Nine. Problem Solver
A state of eight digital problems is actually an arrangement of 0~9, for any given initial state and target, there is not necessarily a solution, that is, from the initial state may not be able to reach the target state. Because there are odd and even permutations of permutations, the odd permutations cannot be converted to even permutations or vice versa.
If a number 0~8 random arrangement 871526340, with F (x) in front of the number x is smaller than it, the sum of the total number of f (x) is Y=∑ (f (x)), if Y is an odd number of the original numbers are arranged in odd order, if Y is an even number, the arrangement of the original numbers is even arranged.
For example 871526340 of this permutation
y=0+0+0+1+1+3+2+3+0=10
10 is an even number, so he arranges in pairs. 871625340
Y=0+0+0+1+1+2+2+3+0=9
9 is odd, so he's odd in rank.
Therefore, you can check the initial state and the target State before running the same embarrassment, the same problem can be solved, you should be able to search the path. Otherwise there is no solution.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.