hdu Safecracker(回溯)

/*

题意:给你一个数target和一个字符串,该字符串由大写字母组成,长度为5到12。大写字母A代表1,B代表2以此类推。。。从字符串中选出5个字母,字母所代表的的数字经过以下公式运算v - w^2 + x^3 - y^4 + z^5 = target。公式成立就输出v -,w,x,y, z所代表的的字符。有可能出现多种情况,以字典倒序排列。

*/

 

//太暴力了,直接枚举
#include<iostream>
#include<algorithm>
using namespace std;
char str[27];

bool cmp(char x, char y)
{
	return x>y;
}

int main()
{
	int num;
	while(scanf("%d", &num) != EOF )
	{
		scanf("%s", str);
		if(num==0 && strcmp(str, "END")==0)
			break;
		int a, b, c, d, e, len;
		len = strlen(str);
		bool p=false;
		sort(str, str+len, cmp);
		for( a=0; a < len; a++ )
		{
			for( b=0; b < len; b++)
			{
				if(a==b) continue;
				for( c=0; c < len; c++ )
				{
					if(c==a || a==b) continue;
					for( d=0; d < len; d++ )
					{
						if(d==a || d==b || d==c) continue;
						for( e=0; e < len; e++ )
						{
							if(e==a || e==b || e==c || e==d) continue;
							int ta, tb, tc, td, te;
							ta = str[a]-'A'+1;
							tb = str[b]-'A'+1;
							tc = str[c]-'A'+1;
							td = str[d]-'A'+1;
							te = str[e]-'A'+1;
							if(ta-tb*tb+tc*tc*tc-td*td*td*td+te*te*te*te*te==num)
							{
								printf("%c%c%c%c%c\n", str[a], str[b], str[c], str[d], str[e]);
								p=true;
								break;
							}
						}
						if(p)
							break;
					}
					if(p)
						break;
				}
				if(p)
					break;
			}
			if(p)
				break;
		}
		if(!p)
			printf("no solution\n");
	}
	return 0;
}
//回溯
#include<iostream>
#include<cmath>
using namespace std;
int num, len;
char t[6], ans[6], str[30];
bool p[30];

void work(int k)
{
	int temp, i;
	if(k==5)
	{
		temp = t[0]-'A'+1 - pow(t[1]-'A'+1, 2) + pow(t[2]-'A'+1, 3) - pow(t[3]-'A'+1, 4) + pow(t[4]-'A'+1, 5);
		if(temp==num && strcmp(t, ans) > 0)
			strcpy(ans, t);
		return ;
	}
	for( i=0; i < len; i++ )
	{
		if(!p[i])
		{
			t[k] = str[i];
			p[i]=true;
			work(k+1);
			p[i] =false;
		}
	}
}

int main()
{
	while(scanf("%d%s", &num, str) && (num || strcmp(str, "END")))
	{
		len = strlen(str);
		memset(t, '\0', sizeof(t));
		memset(ans, '\0', sizeof(ans));
		memset(p, false, sizeof(p));
		work(0);
		if(strlen(ans)==0) printf("no solution\n");
		else printf("%s\n", ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值