Handbook刷到了complete search,在生成排列这节提了一下next_permutation这个方法。
先看看一个简单的例子是如何实现生成排列的
#include <bits/stdc++.h>
using namespace std;
void getPermu(int n){
std::vector<int> v;
for(int i=0; i<n; i++){
v.push_back(i);
}
do{
for(int j=0; j<n; j++){
cout << v[j] << " ";
}
cout << "\n";
}while(next_permutation(v.begin(), v.end()));
cout << "The vector after loop:\n";
for(int j=0; j<n; j++){
cout << v[j] << " ";
}
}
int main(){
int n;
cin >> n;
getPermu(n);
}
function template
std::next_permutation
default (1)
template <class BidirectionalIterator>
bool next_permutation (BidirectionalIterator first, BidirectionalIterator last);
custom (2)
template <class BidirectionalIterator, class Compare>
bool next_permutation (BidirectionalIterator first, BidirectionalIterator last, Compare comp);
Transform range to next permutation
Rearranges the elements in the range [first,last) into the next lexicographically greater permutation.
A permutation is each one of the N! possible arrangements the elements can take (where N is the
number of elements in the range). Different permutations can be ordered according to how they compare lexicographicaly to each other; The first such-sorted possible permutation (the one that would compare lexicographically smaller to all other permutations) is the one which has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order.
The comparisons of individual elements are performed using either operator< for the first version, or comp for the second.
If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If that was not possible (because it is already at the largest possible permutation), it rearranges the elements according to> the first permutation (sorted in ascending order) and returns false.
next_permutation()
的作用是将范围内的元素重新排列为字典上更大的下一个排列。如果函数可以确定下一个更高的排列,则将其按原样重新排列元素并返回true。如果这是不可能的(因为它已经处于最大可能的排列),它将根据第一个排列(按升序排列)重新排列元素并返回false。
在这边比较迷惑的一个是什么是next lexicographically greater。官方文档
lexicographical_compare是这样解释的:序列A和序列B比较,就是对相同位置上的元素进行比较,如果A某位置上的元素比B序列同位置的元素小,那么A序列在字典上就是比B序列小。如果相同位置上的元素一直相等直到短的那个序列结束,那么短的那个序列在字典上就是小的。
嗯以上