pku 3187 Backward Digit Sums

全排列问题,too

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

 

#define MAX 100

 

int N,sum,a[MAX],myhash[MAX],out[MAX],shot[MAX];
bool work;

 

bool calc()
{
    int i=0,j,lim=N;
    for(i=0; i<lim; i++)
        shot[i]=out[i];
    do
    {
        j=0;
        for(i=1; i<lim; i++)
        {
            shot[j++]=shot[i]+shot[i-1];
        }
        lim=j;
    }
    while(j>1);
    if(shot[0]==sum)
        return true;
    return false;
}

void dfs(int cur)
{
    if( !work ) return;
    if(cur == N)
    {
        if( calc() )
        {
            bool first=true;
            for(int i=0; i<N; i++)
            {
                if(first)
                {
                    printf("%d",out[i]);
                    first=false;
                }
                else printf(" %d",out[i]);
            }
            printf("\n");
            work=false;
        }

    }
    for(int i=1; i<=N; i++)
    {
        if(myhash[i]>0)
        {
            out[cur]=i;
            myhash[i]--;
            dfs(cur+1);
            myhash[i]++;
        }
    }
}

int main()
{
    while(scanf("%d %d",&N,&sum)!=EOF)
    {
        if(N==1)
        {
            printf("1\n");
            continue;
        }
        int i;
        for(i=0; i<N; i++)
            a[i]=i+1;
        memset(myhash,0,sizeof(myhash));
        for(i=0; i<N; i++)
            myhash[ a[i] ]++;
        work=true;
        dfs(0);
    }
    return 0;
}

 

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

 

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

 

#define MAX 100

 

int N,sum,a[MAX],out[MAX],shot[MAX];
bool work,used[MAX];

 

bool calc()
{
    int i=0,j,lim=N;
    for(i=0; i<lim; i++)
        shot[i]=out[i];
    do
    {
        j=0;
        for(i=1; i<lim; i++)
        {
            shot[j++]=shot[i]+shot[i-1];
        }
        lim=j;
    }
    while(j>1);
    if(shot[0]==sum)
        return true;
    return false;
}

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

int main()
{
    while(scanf("%d %d",&N,&sum)!=EOF)
    {
        if(N==1)
        {
            printf("1\n");
            continue;
        }
        int i;
        for(i=0; i<N; i++)
            a[i]=i+1;
        memset(used,0,sizeof(used));
        work=true;
        dfs(0);
    }
    return 0;
}

 

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