hdu_1015(dfs)

题意:根据给出的计算公式,给一个n和一个字符集,问能不能在字符串集中找到不重复的五个字符,让其计算结果等于给定的n,如果有多个解输出字典序最大的一个

题解:dfs直接上代码了

code:

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cmath>
 5 using namespace std;
 6 #define ll long long
 7 char ch[28];
 8 char ans[10];
 9 ll n;
10 int len;
11 bool vis[28];
12 bool dfs(ll sum,int tm)
13 {
14     if(sum==n&&tm==5) return true;
15     if(tm==5) return false;
16     for(int i = len-1; i >= 0; i--){
17         if(vis[i]==0){
18             vis[i] = 1;
19             tm++;
20             ans[tm-1] = ch[i];
21             ll tt = pow(-1.0,tm-1)*pow((double)(ch[i]-'A'+1),tm);
22             sum = sum + tt;
23             if(dfs(sum,tm)) return true;
24             sum = sum - tt;
25             tm--;
26             vis[i] = 0;
27         }
28     }
29     return false;
30 }
31 int main()
32 {
33     while(~scanf("%lld",&n))
34     {
35         memset(ch,0,sizeof(ch));
36         scanf("%s",ch);
37         //printf("%s",ch);
38         if(n==0&&!strcmp(ch,"END")) return 0;
39         len = 0;
40         for(int i = 0; ch[i]!=''; i++) len++;
41         sort(ch,ch+len);
42         memset(vis,0,sizeof(vis));
43         if(dfs(0,0)) printf("%s
",ans);
44         else printf("no solution
");
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/shanyr/p/6671923.html