HDU 1015 Safecracker

转载请注明出处忆梦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[N],t[10],ans[10];
 int target,n,a[N];
 bool visited[N];
 
 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;
 }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值