Safecracker

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1015

分析:DFS

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

char s[27], res[6];
int target, ok[27], flag, len;

int cal( char * a )
{
    int t, sum = 0;
    for ( int i = 0; i < 5; i++ )
    {
        t = -1;
        for ( int j = 1; j <= i + 1; j++ )
        {
            t *= -(a[i] - 'A' + 1);
        }
        sum += t;
    }
    return sum;
}

void dfs(int n)
{
    if ( n == 5 )
    {
        res[n] = '\0';
        if ( cal(res) == target )
        {
            flag = 1;
        }
        else
        {
            flag = 0;
        }
        return;
    }
    for ( int i = len - 1; i >= 0; i-- )
    {
        if (!ok[i])
        {
            ok[i] = 1;
            res[n] = s[i];
            dfs(n + 1);
            if (flag)
            {
                return;
            }
            ok[i] = 0;
        }
    }
}

int main()
{
    while ( cin >> target )
    {
        cin.getline( s, 27 );
        if ( target == 0 )
            break;
        memset( ok, 0, sizeof(ok) );
        len = strlen(s);
        flag = 0;
        sort( s + 1, s + strlen(s) );
        dfs(0);
        if (flag)
        {
            cout << res << endl;
        }
        else
        {
            cout << "no solution" << endl;
        }
    }
    return 0;
}

posted on 2012-03-26 16:30  GQHero  阅读(173)  评论(0编辑  收藏  举报

导航