next_permutation(排列问题)

来源:互联网 发布:仓库数据流程图 编辑:程序博客网 时间:2024/05/22 14:32


全排列的模板

#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;

}


计算n个数的第k个排列

#include <bits/stdc++.h>using namespace std;int main(){    int a[1010];    int n,k;    cin>>n>>k;    for(int i=0;i<n;i++) a[i]=i+1;    sort(a,a+n);    int i=0;    while(next_permutation(a,a+n)){        i++;        if(i==k-1) break;    }    for(int i=0;i<n-1;i++) cout<<a[i]<<" ";    cout<<a[n-1]<<endl;    return 0;}


原创粉丝点击