STL之next_permutation和prev_permutation用法及例题

next_permutation和prev_permutation是STL中两个全排列函数

其中 next_permutation表示求下一个按字典序的后一个全排列比如:

      1 2 3  next_permutation  ->1 3 2->2 1 3->2 3 1->3 1 2->3 2 1;

prev_permutation表示求上一个按字典序的全排列:

        3 2 1  prev_permutation ->3 1 2->2 3 1->2 1 3->1 3 2->1 2 3;

(个人理解就是next_permutation最后的结果是序列中的数按降序排列,prev_permutation最后的结果是按升序排列)

例题 hdu 1027 Ignatius and the Princess II

         这题的题意就是,给两个数n k求1-n的全排列序列里第k个是多少

#include <bits/stdc++.h>
#define  int long long
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
const int maxn=2e5+50;
const int INF=0x3f3f3f3f;
using namespace std;
int a[1003];
signed main(){
  IOS;
  int n,k;
  while(cin>>n>>k){
     k-=1;//因为1 2 3 ...n就是第一种形态了;
      for(int i=1;i<=n;i++)a[i]=i;
     while(k--){
         next_permutation(a+1,a+n+1);//需要注意的是这个函数在头文件<algorithm>里面
     } 
    for(int i=1;i<n;i++){
        cout<<a[i]<<" ";
    }
    cout<<a[n];
    cout<<'\n';
  } 
 return 0;
}

例题2 P1088 [NOIP2004 普及组] 火星人

 

 

 

 

#include <bits/stdc++.h>
#define  int long long
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
const int maxn=2e5+50;
const int INF=0x3f3f3f3f;
using namespace std;
int a[10003];
signed main(){
  IOS;
  int n,k;
   cin>>n>>k;
      for(int i=1;i<=n;i++)cin>>a[i];
     while(k--){
         next_permutation(a+1,a+n+1);
     } 
    for(int i=1;i<n;i++){
        cout<<a[i]<<" ";
    }
    cout<<a[n];
    cout<<'\n';
 return 0;
}
View Code

 

 

posted @ 2021-01-31 11:38  小靖快去敲代码  阅读(107)  评论(0编辑  收藏  举报