全排列的模板
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sortint 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;
}