zoukankan      html  css  js  c++  java
  • 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<<'
    ';
      } 
     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<<'
    ';
     return 0;
    }
    View Code

     

  • 相关阅读:
    (原创) mac 10.9.2 eclipse 的 CDT 的 异常的修复
    (转) Virtual function
    (转) ROS NAMING AND NAMESPACES
    (转) Data structures
    (转) Dynamic memory
    java string类
    eclipse 的快捷键
    java抽象类和接口
    面向对象的三大特征
    Java 中的多态
  • 原文地址:https://www.cnblogs.com/ahijing/p/14351925.html
Copyright © 2011-2022 走看看