HDU 1027 Ignatius and the Princess II

http://acm.hdu.edu.cn/showproblem.php?pid=1027

求数列n的第m个排列,STL中next_permutation的应用。相对应的还有prev_permutation。

View Code
#include <iostream>

#include <map>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

    int n,m,i;

    int s[1100];

    while(~scanf("%d%d",&n,&m))

    {

        for(i=1;i<=n;i++)

            s[i]=i;

        while(--m)

            next_permutation(s+1,s+n+1);

        for(i=1;i<n;i++)

            printf("%d ",s[i]);

        printf("%d\n",s[n]);

    }

    return 0;

}

 不过这东西不常用,记不住简直坑爹,还是写个dfs省事儿

#include <iostream>

using namespace std ;

int n,m ;

int vis[1001],ans[1001] ;

int cnt,f ;

void dfs(int cur)

{

    if(f)

        return ;

    if(cur==n)

    {

        cnt++ ;

        if(cnt==m)

        {

            f=1 ;

            for(int i=0 ;i<n ;i++)

            {

                if(!i)

                    printf("%d",ans[i]) ;

                else

                    printf(" %d",ans[i]) ;

            }

            putchar('\n') ;

        }

        return ;

    }

    for(int i=1 ;i<=n ;i++)

    {

        if(!vis[i])

        {

            vis[i]=1 ;

            ans[cur]=i ;

            dfs(cur+1) ;

            vis[i]=0 ;

        }

    }

}

int main()

{

    while(~scanf("%d%d",&n,&m))

    {

        cnt=f=0 ;

        memset(vis,0,sizeof(vis)) ;

        dfs(0) ;

    }

    return 0 ;

}
View Code

 

你可能感兴趣的:(HDU)