1.DFS:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
char str[20], ans[10];
int vis[20], flag;
bool cmp(char a, char b){return a > b;}
void dfs(int dep, int target, int len){
if(dep == 5){
int sum = 0;
for(int i = 1; i <= 5; i ++)
sum += (int)pow(ans[i-1]-'A'+1., i)*(int)pow(-1., i+1);
if(sum == target){
flag = 1;
printf("%s\n", ans);
}
return ;
}
for(int i = 0; i < len; i ++){
if(!vis[i]){
vis[i] = 1;
ans[dep] = str[i];
dfs(dep+1, target, len);
if(flag) return;
vis[i] = 0;
}
}
}
int main(){
int target;
freopen("in.c", "r", stdin);
while(~scanf("%d%s", &target, str) && strcmp(str, "END") && target){
flag = 0;
memset(vis, 0, sizeof(vis));
int len = strlen(str);
sort(str, str+len, cmp);
dfs(0, target, len);
if(!flag) printf("no solution\n");
memset(str, 0, sizeof(str));
}
return 0;
}
2.二进制枚举:
#include
#include
#include
#include
#include
using namespace std;
int main(){
int n, a[20];
string str;
freopen("in.c", "r", stdin);
while(cin >> n >> str && str != "END" && n){
char ans[10] = "A";
int flag = 0;
for(int i = 0;i < (1 << str.size()); i ++){
int cnt = 0, sum = 0;
for(int j = 0; j < str.size(); j ++){
if(i & (1 << j)) a[cnt++] = j;
}
if(cnt == 5){
char tmp[10];
for(int i = 0; i < 5; i ++) tmp[i] = str[a[i]];
sort(tmp, tmp+5);
do{
int sum = 0;
for(int i = 1; i <= 5; i ++)
sum += (int)pow(-1., i+1)*(int)pow(tmp[i-1]-'A'+1., i);
if(sum == n){
flag = 1;
if(strcmp(ans, tmp) < 0) strcpy(ans, tmp);
}
}while(next_permutation(tmp, tmp+cnt));
}
}
if(flag) printf("%s\n", ans);
else cout << "no solution" << endl;
}
return 0;
}