stl 生成排列
首先列出cplusplus的定义和范例
template <class BidirectionalIterator> bool next_permutation (BidirectionalIterator first, BidirectionalIterator last ); template <class BidirectionalIterator, class Compare> bool next_permutation (BidirectionalIterator first, BidirectionalIterator last, Compare comp);
范例程序:
// next_permutation
#include <iostream>
#include <algorithm>
using namespace std;
int main () {
int myints[] = {1,2,3};
cout << "The 3! possible permutations with 3 elements:\n";
sort (myints,myints+3);
do {
cout << myints[0] << " " << myints[1] << " " << myints[2] << endl;
} while ( next_permutation (myints,myints+3) );
return 0;
}
下面给出我的一条代码:
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
int const maxn = 10;
int a[maxn], n;
int main()
{
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i];
while (std::next_permutation(a,a+n))
{
for (int i = 0; i < n; ++i)
cout << a[i] << ' ';
cout << endl;
}
}
样例输入:
5
2 3 3 3 1
output:
5
2 3 3 3 1
3 1 2 3 3
3 1 3 3 2
3 2 1 3 3
3 2 3 1 3
3 2 3 3 1
3 3 1 2 3
3 3 2 1 3
3 3 2 3 1
3 3 3 1 2
3 3 3 2 1
标准IO限定加速
std::ios_base::sync_with_stdio
如果又同学经常做poj或spoj, IO 操作便会成为一个头疼的大问题~~TLE
为什么?? spoj 太慢 ~! poj 卡stl?!
其实部分原因是c++ 的标准IO 与 C standard的 IO 相关联,使得IO操作变慢了
这个问题其实又 2 个解决办法,不用c++ 的IO,直接用stdio.h
还有一个就是下面要说的办法:
再使用IO操作前,加上这么一句:
std::io_base::sync_with_stdio(false);
切断与stdio 的联系
这样就得到一个常数级别的提升,如此读入的速度应该与 prinf() scanf() 的速度相接近了。
注意: 这个是ios_base 里面的 static 变量