您的位置:首页 > 其它

next_permutation(排列问题)

2017-08-02 22:12 260 查看
全排列的模板

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: