stl 生成排列 && 标准IO的限定加速

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;
}



其实这个范例有点误导人,因为myints[] 不一定要是1~n 的 , 任意数都是可行的(当然又重复也会处理哦!)

下面给出我的一条代码:

#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 变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值