hdu 1027 Ignatius and the Princess II

又是简单的全排列问题

//STL模板
#include <stdio.h>
#include <algorithm>

using namespace std;

 

#define MAX 1005

 

int N,M,a[MAX];

 

int main(void)
{
    while(scanf("%d %d",&N,&M)!=EOF)
    {
        int i;
        for(i=1; i<=N; i++)
            a[i]=i;
        for(i=1; i<M; i++)
            next_permutation(a+1,a+N+1);
        printf("%d",a[1]);
        for(i=2; i<=N; i++)
            printf(" %d",a[i]);
        printf("\n");
    }
    return 0;
}


//************************************************************************************************


//法2

#include <stdio.h>
#include <string.h>

 

#define MAX 1005

 

int N,M,cnt,a[MAX],out[MAX];
bool work,used[MAX];

 

void dfs(int cur)
{
    if(!work) return;
    if( cur == N)
    {
        if(++cnt >= M)
        {
            work=false;
            printf("%d",out[0]);
            for(int i=1; i<N; i++)
                printf(" %d",out[i]);
            printf("\n");
        }
    }
    else
        for(int i=0; i<N; i++)
        {
            if(!used[i])
            {
                used[i]=true;
                out[cur]=a[i];
                dfs(cur+1);
                used[i]=false;
            }
        }
}

int main()
{
    while(scanf("%d %d",&N,&M)!=EOF)
    {
        int i;
        for(i=0; i<N; i++)
            a[i]=i+1;
        memset(used,false,sizeof(used));
        cnt=0;
        work=true;
        dfs(0);
    }
    return 0;
}

 

//************************************************************************************************


//法3 hash

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

#define SIZE 1005
#define HASHSIZE 1005

int N,M,cnt,a[SIZE],hash[HASHSIZE],out[SIZE];
bool work;

void dfs(int cur)
{
    if(!work) return ;
    if(cur==N)
    {
        if(++cnt==M)
        {
            work=false;
            printf("%d",out[0]);
            for(int i=1; i<N; i++)
                printf(" %d",out[i]);
            printf("\n");
        }
    }
    else
        for(int i=0; i<=a[N-1]; i++)
        {
            if(hash[i]>0)
            {
                out[cur]=i;
                hash[i]--;
                dfs(cur+1);
                hash[i]++;
            }
        }
}

int main()
{
    while(scanf("%d %d",&N,&M)!=EOF)
    {
        int i;
        for(i=0; i<N; i++)
            a[i]=i+1;
        memset(hash,0,sizeof(hash));
        for(i=0; i<N; i++)
            hash[ a[i] ]++;
        work=true;
        cnt=0;
        dfs(0);
    }
    return 0;
}

 

posted @ 2010-08-18 13:44  菜到不得鸟  阅读(358)  评论(0)    收藏  举报