HDU 1027 Ignatius and the Princess II(stl,next_permutation)

来源:互联网 发布:苹果手机怎么信任软件 编辑:程序博客网 时间:2024/05/01 15:57

HDU 1027 Ignatius and the Princess II
题目:求N个数全排列,顺着数第M个
next_permutation(a,a+n),这是我第一次用这个神奇的函数。以前根本不知道还有这种,能够进行全排列的函数,
与之完全相反的函数还有prev_permutation
a[0]=1;a[1]=2;a[2]=3;
do{cout << a[0]<< ” ” << a[1]<<” “<< a[2]<< endl;}while (next_permutation(a,a+3));
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果改成 while(next_permutation(a,a+2));
则输出:
1 2 3
2 1 3
只对前两个元素进行字典排序
这是一道非常简单的题目,代码如下

#include <iostream>#include <string.h>#include <algorithm>using namespace std;long long n,m,num;int a[1005];int main(){    ios::sync_with_stdio(false);    while(cin>>n>>m)    {        num=1;        memset(a,0,sizeof(a));        for(int i=0; i<n; i++)        {            a[i]=i+1;        }        do{//这里要用do  while            if(num==m)            {                for(int i=0; i<n-1; i++)                {                    cout<<a[i]<<" ";                }                cout<<a[n-1];                cout<<endl;                //break;            }             num++;             if(num>m)                break;        }while(next_permutation(a,a+n));    }    return 0;}
0 0
原创粉丝点击