STL next_permutation(全排列算法)

#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::next_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}


Output:

The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3



同理这个可以直接按字符串来输入输出:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int main()
{
	char a[2000];
	cout<<"输入的数为:";
	cin>>a;
	cout<<"输出为:"<<endl;
	do{
		cout<<a<<endl;
	}while(next_permutation(a,a+strlen(a)));
	return 0;
}


然后下面有一个例题,来更好地理解一下这个函数:

n个人排成一队,队头的人编号为1,后面的人编号分别为2,3,…,n. 1号人前面没有人,i号人的前面是i-1。 现在Kim想让这n个人重新排队,要求重新排队后编号为i的人前面不能是i-1。问有多少种排队的方法。

这个题假设n在10以内(这个例子只是用来理解next_permutation)

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100];

int main()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++)  a[i]=i+1;
	int sum=0;
	while(next_permutation(a,a+n))
	{
		int flag=0;
		for(int i=1;i<n;i++)
		{
			if(a[i]==a[i-1]+1)
			{
				flag=1;
				break;
			}
		}
		if(flag)  continue;
		else sum++;
	}
	cout<<sum<<endl;
}
这个首先如果n=5,数列a的顺序是1 2 3 4 5.不满足题意,所以sum初值是0,然后next_permutation就会按着字典序输出a数组的下一个顺序.知道全部输入完为止.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值