zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Redis常见数据类型
    MYSQL常见可优化场景
    算术切片
    找数组里没出现的数
    不同路径和(II)
    不同路径和
    最小路径和
    强盗抢房子
    丑数(2)
    判断子序列
  • 原文地址:https://www.cnblogs.com/xiaohongmao/p/2494685.html
Copyright © 2011-2022 走看看