hdu_1015(dfs)

本文介绍了一个基于深度优先搜索(DFS)算法解决特定字符计算问题的方法。问题要求从给定字符集中找出五个不同的字符,使得按照特定公式计算的结果等于给定数值n。通过递归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]!='\0'; i++) len++;
41         sort(ch,ch+len);
42         memset(vis,0,sizeof(vis));
43         if(dfs(0,0)) printf("%s\n",ans);
44         else printf("no solution\n");
45     }
46     return 0;
47 }

 

转载于:https://www.cnblogs.com/shanyr/p/6671923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值