Problem description:
Please writeProgramSolve the basketball error Sorting Problem. We know that N baskets are exclusive (N is any positive integer input by the user), marked with numbers 1, 2,..., from left to right ,......, n; each ball also has a number, which is also 1, 2 ,......, n. Now we want to put all the N balls in these N baskets. If you want to put one ball in each basket, the number of the ball cannot be the same as the number of the basket, the number of balls in the adjacent basket cannot be adjacent. For example, if the numbers of balls in the two adjacent baskets are 9 and 10, they are not allowed. Please output all ball-dropping methods that meet the requirements (for each ball-dropping method that meets the requirements, the number of balls in each basket should be output ).
Program:
The Solution Below is very easy to understand. In fact, the solution is to determine whether the current full sorting meets the error sorting conditions. If yes, the current sorting will be output ......
============
# Include <iostream>
Using namespace STD;
Static int COUNT = 0;
// determine whether the current arrangement a [] meets the error sorting condition
bool validate (int A [], int size)
{< br> // whether the first is in the first position, or whether the first and second are adjacent
if (a [0] = 1 | [0] = A [1] + 1 | A [0] = A [1]-1)
return false;
// determine whether the last and last are in the last position, or whether the last and last are adjacent
if (a [size-1] = size | | A [size-1] = A [size-2] + 1 | A [size-1] = A [size-2]-1)
return false;
// whether the center is at the corresponding position, or is adjacent to the front and back positions
for (INT I = 2; I <= size-1; I ++)
{
if (a [I-1] = I | A [I-1] = A [I-2] + 1 | A [I-1] = [i-2]-1 |
A [I-1] = A [I] + 1 | A [I-1] = A [I]-1)
return false;
}< br> return true;
}
// arrange all the elements between K and m in the subscript of, output an array that meets the error sorting condition
void permuta (int A [], int K, int M, int num)
{< br> If (k = m)
{< br> If (validate (A, num )) // if the current sorting condition is met,
{< br> count ++;
// print the result
for (int K = 0; k cout cout }< BR >}< br> else
{< br> for (INT I = K; I <= m; I ++)
{< br> swap (A [K], a [I]);
permuta (A, K + 1, m, num );
swap (A [K], a [I]);
}< BR >}
int main ()
{< br> int num;
cout <"input num:";
CIN> num;
int * Per = new int [num];
for (INT I = 0; I Per [I] = I + 1;
permuta (Per, 0, NUM-1, num );
cout return 0;
}