天天看點

全排列next_permutation函數

POJ1833 全排列問題

檢視題目點選此連結

分析:

此問題用到next_permutation函數則很容易

next_permutation函數是求目前排列的下一個排列

next_permutation(a,a+n);//求下一個排列
prev_permutation(a,a+n);//求上一個排列
//如果沒有上一個排列或下一個排列則傳回false,否則true
//還可以定義cmp來定義排列的方式next_permutation(a,a+n,cmp)
           

知道了這個函數那麼題目就簡單了很多

include<iostream>
include<iterator>
include<algorithm>

using namespace std;

const int N=1024;
int a[N];
int main()
{
    int m,n,k;
    cin>>m;
    while(m--)
    {
        cin>>n>>k;
        for(int i=0;i<n;i++)
            cin>>a[i];
        for(int i=1;i<=k;i++)
            //利用STL函數庫中的計算全排列的函數計算
            next_permutation(a,a+n);
        //如果使用cout循環輸出,則出現TLE
        //使用copy函數輸出容器中的内容
        //container<type> c;
        //copy(c.begin(),c.end(),ostream_iterator<type>(cout," "));
        copy(a,a+n-1,ostream_iterator<int>(cout," "));
        cout<<a[n-1]<<endl;
    }
    return 0;
}
           
STL