直接上15ms代码,还没想好记忆化怎么弄 应该还能更快一点
AC代码如下:
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
char s[2000],sr[2000];
int res,book[20],n,flag;
int cmp(char a,char b)
{
return a>b;
}
void dfs(int k,int sum,int q)
{
if(k==6)
{
if(res==sum)
{
flag=1;
sr[k-1]=0;
return ;
}
return ;
}
int i,z;
for(i=0;i<n;i++)
{
if(!book[i])
{
z=s[i]-'A'+1;
book[i]=1;
sr[k-1]=s[i];
dfs(k+1,sum+q*pow(z,k),-q);
if(flag) return ;
sr[k-1]=0;
book[i]=0;
}
}
return ;
}
int main()
{
while(cin>>res>>s && (res||strcmp(s,"END")))
{
n=strlen(s);
flag=0;
memset(book,0,sizeof(book));
sort(s,s+n,cmp);
//先把结果不能达到的筛掉
if(pow(s[0]-'A'+1,5)+pow(s[1]-'A'+1,4)+pow(s[2]-'A'+1,3)-pow(s[n-1]-'A'+1,2)-pow(s[n-2]-'A'+1,1)<res ||
pow(s[n-1]-'A'+1,5)+pow(s[n-2]-'A'+1,4)+pow(s[n-3]-'A'+1,3)-pow(s[0]-'A'+1,2)-pow(s[1]-'A'+1,1)>res)
{
cout<<"no solution"<<endl;
continue;
}
dfs(1,0,1);
if(flag)
cout<<sr<<endl;
else
cout<<"no solution"<<endl;
}
return 0;
}