题目大意
输入一个数字和一个字符串,字符串中的每个字母代表一个数字,问能否用这些数字的组合得到满足公式v - w^2 + x^3 - y^4 + z^5 = target的解。
题目解法
这道题我用了hash表的思想,将字母hash成对应的数字,然后不断枚举得到一个满足解就可以了,因为要求字典序最大,所以要从大到小枚举。因为最多26的字母,5次循环不会超时,暴力就可以了。因为要找到一个解就行了,所以要跳出5重循环,我使用了goto,我也不会,在网上看了别人怎么用的就学会了!!
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
char str[30];
int has[30]; //hash值
int main()
{
int sum;
while(scanf("%d %s", &sum, str) != EOF && sum)
{
int len = strlen(str);
memset(has, 0, sizeof(has));
for(int i = 0; i < len; i++)
has[str[i]-'A'+1]++;
int flag = 0;
for(int v = 26; v > 0; v--)
{
if(has[v])
{
has[v]--;
for(int w = 26; w > 0; w--)
{
if(has[w])
{
has[w]--;
for(int x = 26; x > 0; x--)
{
if(has[x])
{
has[x]--;
for(int y = 26; y > 0; y--)
{
if(has[y])
{
has[y]--;
for(int z = 26; z > 0; z--)
{
if(has[z] && (v - w*w + x*x*x - y*y*y*y + z*z*z*z*z == sum))
{
printf("%c%c%c%c%c\n",v-1+'A',w-1+'A',x-1+'A',y-1+'A',z-1+'A');
flag = 1;
goto finally;
}
}
has[y]++;
}
}
has[x]++;
}
}
has[w]++;
}
}
has[v]++;
}
}
finally:
if(!flag) printf("no solution\n");
}
return 0;
}