题目链接:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=108&page=show_problem&problem=267
题目类型: 回溯
原题:
Sorting an array can be done by swapping certain pairs of adjacent entries in the array. This is the fundamental technique used in the well-known bubble sort. If we list the identities of the pairs to be swapped, in the sequence they are to be swapped, we obtain what might be called a swap map. For example, suppose we wish to sort the array A whose elements are 3, 2, and 1 in that order. If the subscripts for this array are 1, 2, and 3, sorting the array can be accomplished by swapping A2 and A3, then swapping A1 and A2, and finally swapping A2 and A3. If a pair is identified in a swap map by indicating the subscript of the first element of the pair to be swapped, then this sorting process would be characterized with the swap map 2 1 2.
It is instructive to note that there may be many ways in which swapping of adjacent array entries can be used to sort an array. The previous array, containing 3 2 1, could also be sorted by swapping A1 and A2, then swapping A2 and A3, and finally swapping 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 will show that there are an infinite number of swap maps, since sequential swapping of an arbitrary pair of elements will not change the order of the elements. Thus the swap map 1 1 1 2 1 will also leave our array elements in ascending order. But how many swap maps of minimum size will place a given array in order? That is the question you are to answer in this problem.
题目大意:
给定一个数字序列,然后要你用交换相邻两个数的方法, 用最少交换次数进行排序的方案数有多少种
分析与总结:
首先,用冒泡排序的方法一定是交换次数最少的方案。那么只要进行简单的暴力搜索出所有交换方案即可。
#include<iostream> #include<cstdio> #include<cstring> #define MAXN 7 using namespace std; bool vis[MAXN], flag; int minSwap,arr[MAXN], n; void swap(int &a,int &b){int t=a; a=b; b=t;} inline bool isAccend(){ for(int i=2; i<=n; ++i) if(arr[i] < arr[i-1]) return false; return true; } void dfs(){ if(isAccend()){ ++minSwap; return; } for(int i=1; i<n; ++i){ if(arr[i] > arr[i+1]) { swap(arr[i], arr[i+1]); dfs(); swap(arr[i], arr[i+1]); } } } int main(){ #ifdef LOCAL freopen("input.txt","r",stdin); #endif int cas=1; arr[0] = -99999; while(scanf("%d", &n), n){ for(int i=1; i<=n; ++i) scanf("%d", &arr[i]); minSwap=0; if(!isAccend()) dfs(); printf("There are %d swap maps for input data set %d.\n", minSwap, cas++); } return 0; }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索array
, elements
, and
, The
, be
swap
,以便于您获取更多的相关知识。