Safecracker(HD1015)dfs

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1015

 

思路:深度优先搜索,要注意的是先给字符串进行排序,然后从后往前找,这样就能第一个就找到符合题意的。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int target,len,flag;
char str[15],res[10];
int vis[15];

void dfs(int cal, int cnt)
{
    if(cal == target && cnt == 6) //找到了就退出,记得给str加结束符
    {
        flag = 1;
        str[cnt] = '\0';
        return ;
    }
    if(cnt == 6) //超过5个字符还没找到的话就不用找了
        return ;
    for(int i=len-1; i>=0; i--)
    {
        if(!vis[i])
        {
            int num = str[i] - 'A' + 1;
            res[cnt] = str[i];

            int temp = 1,cur = cnt,x = 1;
            if(cnt%2 == 0) //根据第几个确定符号
                temp = -1;
            while(cur--)
                x *= num;
            cal = cal + temp * x;
            cnt ++;
            vis[i] = 1;
            dfs(cal, cnt);
            cal = cal - temp * x;
            cnt --;
            vis[i] = 0;
            if(flag)    //如果找到了就不用往下找了
                return ;
        }
    }
}

int main()
{
    while(scanf("%d%s",&target,str) != EOF)
    {
        if(target == 0 && !strcmp(str,"END")) break;
        len = strlen(str);
        memset(vis, 0 ,sizeof(vis));
        flag = 0;
        sort(str,str+len);  //排序后从后往前找
        for(int i=len-1; i>=0; i--)
        {
            vis[i] = 1;
            int cnt = 2;
            int cal = str[i] - 'A' + 1;
            res[1] = str[i];    //从下标1开始存储
            dfs(cal,cnt);
            vis[i] = 0;
            if(flag) break;
        }
        if(flag)
        {
            for(int i=1; i<6; i++)
                printf("%c",res[i]);
            printf("\n");
        }
        else
            printf("no solution\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值