HDOJ 1015 Safecracker

      题目不具有单调性,所以求导可以忽略。考虑参数在有限的可选值之中,所以可以选择了深度优先。确定搜索变量为5个参数,然后进行深度优先搜索,并在深度为5时终止搜索,判断状态。

View Code
 1 #include <algorithm>
2 #include<cmath>
3 using namespace std;
4 #include<stdio.h>
5 #include <string.h>
6 int target,len;
7 char value[13];
8 bool pruning[13];
9 int result[5];
10 bool flag;
11 inline bool cmp(char a,char b)
12 {
13 return a>b;
14 }
15 inline bool achieveAim()
16 {
17 return result[0]-pow((double)result[1],2)+pow((double)result[2],3)-pow((double)result[3],4)+pow((double)result[4],5) ==target;
18 }
19 inline void dfs(int deep)
20 {
21 if(deep==5)
22 {
23 if(achieveAim())
24 flag=true;
25 return;
26 }
27 for (int i=0;i<len;i++)
28 {
29 if(flag)
30 return;
31 if(pruning[i])
32 continue;
33 result[deep]=value[i];
34 pruning[i]=true;
35 dfs(deep+1);
36 pruning[i]=false;
37 }
38 }
39 int main()
40 {
41 //freopen("Safecracker.txt","r",stdin);
42 while (true)
43 {
44 memset(value,0,sizeof(value));
45 memset(pruning,0,sizeof(pruning));
46 flag=false;
47 scanf("%d",&target);
48 getchar();
49 gets(value);
50 if (target==0&&strcmp(value,"END")==0)
51 break;
52 len=strlen(value);
53 for (int i=0;i<len;i++)
54 value[i]-=('A'-1);
55 sort(value,value+len,cmp);
56 dfs(0);
57 if(flag)
58 printf("%c%c%c%c%c\n",result[0]+'A'-1,result[1]+'A'-1,result[2]+'A'-1,result[3]+'A'-1,result[4]+'A'-1);
59 else
60 printf("no solution\n");
61 }
62 return 0;
63 }



posted on 2011-10-08 17:31  AdaByron  阅读(386)  评论(0编辑  收藏  举报

导航