C++STL中库函数next_permutation的用法

概述与分析
首先说一句STLyyds!!!

简单说next_permutation()可以按照字典序实现全排列,包含于头文件<algorithm>

例如数组{1,2,3}:

按照字典序全排列为:123,132,213,231,312,321


例如字符串adc:

按照字典序全排列为:abc,acb,bac,bca,cab,cba

 

对于数组代码如下:

do
{

}while(next_permutation(a,a+n));

对于字符串代码如下:

do
{

}while(next_permutation(a.begin(),a,end()));

 

例题

例题1、原题链接:Acwing.823排列

 

 

若是在此之前不知道next_permutation函数,可直接dfs爆搜,代码如下:

#include<iostream>
using namespace std;
const int N=10;
int n;

void dfs(int u,int nums[],bool st[])
{
    if(u>n)
    {
        for(int i=1;i<=n;i++)
        {
            cout<<nums[i]<<' ';
        }
        cout<<endl;
    }
    else
    {
        for(int i=1;i<=n;i++)
        {
            if(!st[i])
            {
                st[i]=true;
                nums[u]=i;
                dfs(u+1,nums,st);
                st[i]=false;//恢复现场 
            }
        }
    }
}
int main() { cin>>n; int nums[N]; bool st[N]={0}; dfs(1,nums,st); return 0; }

可见代码难度较高不便理解(但也要会哦)

接下来使用next_permutation函数,代码如下:

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

int main ()
{
    int n;
    cin >> n;
    for (int i = 1 ; i <= n ; i ++ ) a[i] = i;
    
    do
    {
        for (int i = 1 ; i <= n ; i ++ ) cout << a[i] << ' ' ;
        cout << endl;
    }while(next_permutation(a+1,a+n+1));
return 0; }

 

例题2、ABC201A

 

 

 

针对给出的三个数字,将此三个数字用next_permutation函数实现全排列,依次遍历,若符合a[3]-a[2]=a[2]-a[1],即输出Yes,若没有符合条件的排列,则输出No即可

代码如下:

#include <bits/stdc++.h>
using namespace std;
 
const int N = 3;
int a[N];
 
int main ()
{
	for (int i = 0 ; i < 3 ; i ++ ) cin >> a[i];
  	if (a[0] == a[1] && a[0] == a[2] && a[1] == a[2])
    {
      cout << "Yes" ;
      return 0;
    }
    
	do
	{
		if ((a[2] - a[1]) == (a[1] - a[0]))
		{
			cout << "Yes" ;
			return 0;
		}
	}while(next_permutation(a,a+3));
	
	cout << "No";
	
	return 0;
}

总结:

STLyyds!!!

posted @ 2021-06-08 15:40  CooLevin  阅读(207)  评论(0)    收藏  举报