个人在做了hdu 1027之后觉得通过代码来直接操作实现一组数的递增递减实在是太牛,我没法很好的运用,所以还是好
好用 STL 的现成的比较好吧,那么介绍一下这两个究竟该怎么用吧。
#include <algorithm>
bool next_permutation( iterator start, iterator end );
The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.
这段英文的意思它返回的是布尔型的,true or false,对于next_permutation这种类型来说,举个例子,123这组数列,当换到321时,已经不能再大了,所以返回false;
实现原理是
在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列了。
prev_permutation也是同样的相似的想法。
简单代码如下
int main(){
int a[] = {3,1,2};
do{
cout << a[0] << " " << a[1] << " " << a[2] << endl;
}
while (next_permutation(a,a+3));
return 0;
}
可以通过for循环来实现变换次数,如 hdu 1027