蓝桥杯--枚举、全排列

一、next_permutation()函数

      next_permutation函数用于生成当前序列的下一个排列。它按照字典序对序列进行重新排列,如果存在下一个排列,则将当前序列更改为下一个排列,并返回true;如果当前序列已经是最后一个排列,则将序列更改为第一个排列,并返回 false。

 
#include<bits/stdc++.h>
using namespace std;
int main()
{
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	int n,arr[10];
	cin>>n;
	for(int i=0;i<n;++i)
	{
		cin>>arr[i];
	}
	 bool tag=true;
	 while(tag)
	 {
	 		for(int i=0;i<n;++i)
	      {
	        	cout<<arr[i]<<" ";
	      }
	      	cout<<"\n";
	 	tag=next_permutation(arr,arr+n);
	 }
	return 0;
}

next_permutation函数进行了全排列并以从小到大的升序进行全排列。

二、prev_permutation函数

       prev_permutation函数与next_permutation 函数相反,它用于生成当前序列的上一个排列。它按照字典序对序列进行重新排列,如果存在上一个排列,则将当前序列更改为上一个排列,并返回true;如果当前序列已经是第一个排列,则将序列更改为最后一个排列,并返回false。

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,arr[10];
	cin>>n;
	for(int i=0;i<n;++i)
  {
	    cin>>arr[i];	
  }  	
	do{
		for(int i=0;i<n;++i) cout<<arr[i]<<" ";
		cout<<endl; 
	}while(prev_permutation(arr,arr+n));
	return 0;
}

next_permutation函数进行了全排列并以从大到小的升序进行全排列。

三、例题

(1)思路:

     由题意知,最小的值为12345其大小代表为1,12354其大小代表为2,其中最大值54321代表为120,该题将给出的数字进行全排列,并且排列顺序从小到大按顺序排列,则用c++,STL中next_permutation函数。

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n,m,a[10000];
  cin>>n>>m;
  for(int i=1;i<=n;++i)
  {
    cin>>a[i];
  }
for(int i=1;i<m;++i)
{
next_permutation(a+1,a+n+1);
}
 for(int i=1;i<=n;++i)
 {
  cout<<a[i]<<" ";
 }

  return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值