HDU 1015 Safecracker
2013-07-25 02:35
197 查看
转载请注明出处:忆梦http://blog.csdn.net/fjy4328286/article/details/9460051
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1015题目大意:给你一个target数 和 一串字符串,这串字符都是A~Z,并且规定A~Z分别代表1~26。要求从这一串字符中找出5个字符(而且要是按字典序排序最大的)使得此公式成立 v - w^2 + x^3 - y^4 + z^5 = target ,否则输出no
solution。
题解:之所以说此题很水,因为数据规模不大,5重循环就可以搞定,这是一种方法。 还有一种方法就是回溯。
方法1:15ms
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<algorithm> using namespace std; char fun[5]; int pan() { int i, j; for(i = 0; i < 5 ; i++) for(j = i + 1; j < 5; j++) { if(fun[i] == fun[j]) return 0; } return 1; } int main () { int n; char s[30]; while(scanf("%d%s",&n,s) ,(n||strcmp(s,"END")!=0)) { int flag = 0; int a , b, c, d, e; int len = strlen(s); sort(s,s+len); for(a = len-1; a >= 0 && !flag; a--) for(b = len-1; b >= 0 && !flag; b--) for(c = len-1; c >= 0 && !flag; c--) for(d = len-1; d >= 0 && !flag; d--) for(e = len-1; e >= 0 && !flag; e--) { int temp = s[a] - 'A'+1 - pow(s[b]- 'A' +1,2) + pow(s[c]- 'A'+1,3) - pow(s[d]- 'A'+1,4) + pow(s[e]- 'A'+1,5); if(n == temp) { fun[0] = s[a]; fun[1] = s[b]; fun[2] = s[c]; fun[3] = s[d]; fun[4] = s[e]; if(pan() == 1) { flag = 1; break; } } } if(!flag) printf("no solution\n"); else printf("%c%c%c%c%c\n",fun[0],fun[1],fun[2],fun[3],fun[4]); } return 0; }
方法2:借鉴他人代码 93ms
#include<iostream> #include<cmath> #include<cstring> #define N 30 using namespace std; char s ,t[10],ans[10]; int target,n,a ; bool visited ; void work(int k) { int temp,i; if(k==5) { temp=a[t[0]-'A']-pow(a[t[1]-'A'],2)+pow(a[t[2]-'A'],3)-pow(a[t[3]-'A'],4)+pow(a[t[4]-'A'],5); if(temp==target&&strcmp(t,ans)>0) { strcpy(ans,t); } return ; } for(i=0;i<n;i++) { if(!visited[s[i]-'A']) { t[k]=s[i]; visited[s[i]-'A']=true; work(k+1); visited[s[i]-'A']=false; } } } int main() { int i; for(i=0;i<26;i++) a[i]=i+1; while(cin>>target>>s&&(target||strcmp(s,"END"))) { memset(visited,false,sizeof(visited)); memset(ans,'\0',sizeof(ans)); memset(t,'\0',sizeof(t)); n=strlen(s); work(0); if(strlen(ans)==0) cout<<"no solution"<<endl; else cout<<ans<<endl; } return 0; }
相关文章推荐
- hdu 1015 Safecracker
- hdu 1015 Safecracker
- HDU 1015 Safecracker(DFS)
- HDU - 1015 Safecracker
- HDU-1015-Safecracker(Java && 暴力大法好 && 简单字典序)
- HDU 1015 Safecracker(DFS)
- hdu 1015 Safecracker
- HDU 1015 Safecracker(一道很好的dfs)
- HDU-1015-Safecracker
- <原创> hdu 1015 Safecracker
- hdu 1015 Safecracker
- hdu 1015 Safecracker
- HDU 1015--Safecracker【DFS】
- HDU 1015 Safecracker 解决问题的方法
- hdu 1015 Safecracker 解题报告
- HDU-1015-Safecracker
- HDU 1015 Safecracker
- HDU 1015 Safecracker
- hdu 1015 Safecracker
- HDU 1015 Safecracker