331-mapping the Swaps
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=108&page=show_ problem&problem=267
Sorting an array can do by swapping certain pairs of adjacent in the array. This is the fundamental technique used well-known bubble sort. If We list the identities of the pairs to is swapped, in the sequence they are to be swapped, we obtain what is call Ed a swap map. For example, suppose we wish to sort the array A whose elements are 3, 2, and 1 in. If the subscripts for this array are 1, 2, and 3, sorting the array can is accomplished by swapping A2 and A3, then Swappi Ng A1 and A2, and finally swapping A2 and A3. If a pair is identified into a swap map by indicating the subscript of the ' the ' of the ' pair to be swapped, then thi s sorting process would be characterized with the swap map 2 1 2.
It is instructive to "there may" many ways in which swapping of adjacent array entries can being used to sort a Rray. The previous array, containing 3 2 1, could also is sorted by swapping A1 and A2, then swapping and A2, and finally A3 Pping A1 and A2 again. The swap map that describes this sorting sequence is 1 2 1.
For a given array, how many different swap maps exist? A little thought'll show this there are an infinite number of swap maps, since sequential swapping of a arbitrary pair The elements won't change the order of the elements. Thus the Swap map 1 1 1 2 1 would also leave our array elements in ascending order. But How many swap maps of minimum size to place a given array in order? That's the question you are to answer in this problem.
Input
The input data would contain an arbitrary number of test cases and followed by a single 0. Each test case would have a integer n that gives the size of a array, and would be followed by the n integer values in the Array.
Output
For each test case, print a message similar to those shown in the sample output below. In no test case would n be larger than 5.
Sample Input
2 9 7
2 12 50
3 3 2 1
3 9 1 5
0
Sample Output
There are 1 swap maps for input data set 1.
There are 0 swap maps for input data set 2.
There are 2 swap maps for input data set 3.
There are 1 swap maps for input data set 4.
Water problem.
Complete code:
/*0.013s*/#include <cstdio> #include <algorithm> using namespace std;
int a[10], CNT, n;
void Dfs () {int i;
bool sorted = true;
for (i = 0; i < n-1 ++i) if (A[i] > a[i + 1]) {sorted = false;
Swap (A[i], a[i + 1]);
DFS ();
Swap (A[i], a[i + 1]);
} if (sorted) ++cnt;
int main () {int cas = 0, I;
while (scanf ("%d", &n), N) {for (i = 0; i < n; ++i) scanf ("%d", &a[i]);
CNT = 0;
for (i = 0; i < n-1 ++i) if (a[i) > a[i + 1])///is not in the first line, then DFS ~ {
DFS ();
Break
printf ("There are%d swap maps for input data set%d.\n", CNT, ++cas);
return 0; }
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/