HDU 1015 Safecracker(DFS)

题目链接

普通的DFS。。。输出字典序最大的。。。我竟然没注意。。

#include <stdio.h>

#include <string.h>

char p[31],o[31],max[31];

int k[31];

int ans,z,len;

void dfs(int step,int sum)

{

    int i;

    if(step == 5&&sum == ans)

    {

        z = 1;

        o[5] = '\0';

        if(strcmp(o,max) > 0)

        {

            strcpy(max,o);

        }

        return ;

    }

    if(step > 5)

    return ;

    for(i = 0;i <= len-1;i ++)

    {

        if(!k[i])

        {

            k[i] = 1;

            o[step] = p[i];

            if(step == 0)

            dfs(step+1,sum+p[i]-'A'+1);

            else if(step == 1)

            dfs(step+1,sum-(p[i]-'A'+1)*(p[i]-'A'+1));

            else if(step == 2)

            dfs(step+1,sum+(p[i]-'A'+1)*(p[i]-'A'+1)*(p[i]-'A'+1));

            else if(step == 3)

            dfs(step+1,sum-(p[i]-'A'+1)*(p[i]-'A'+1)*(p[i]-'A'+1)*(p[i]-'A'+1));

            else if(step == 4)

            dfs(step+1,sum+(p[i]-'A'+1)*(p[i]-'A'+1)*(p[i]-'A'+1)*(p[i]-'A'+1)*(p[i]-'A'+1));

            k[i] = 0;

        }

    }

    return ;

}

int main()

{

    int i,j;

    while(scanf("%d%s",&ans,p)!=EOF)

    {

        memset(o,0,sizeof(o));

        memset(k,0,sizeof(k));

        memset(max,0,sizeof(max));

        z = 0;

        len = strlen(p);

        if(ans == 0&&strcmp(p,"END") == 0)

        break;

        dfs(0,0);

        if(!z)

        printf("no solution\n");

        else

        printf("%s\n",max);

    }

    return 0;

}

你可能感兴趣的:(rack)