链接:http://acm.hdu.edu.cn/showproblem.php?pid=1015
思路:深度优先搜索,要注意的是先给字符串进行排序,然后从后往前找,这样就能第一个就找到符合题意的。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int target,len,flag;
char str[15],res[10];
int vis[15];
void dfs(int cal, int cnt)
{
if(cal == target && cnt == 6) //找到了就退出,记得给str加结束符
{
flag = 1;
str[cnt] = '\0';
return ;
}
if(cnt == 6) //超过5个字符还没找到的话就不用找了
return ;
for(int i=len-1; i>=0; i--)
{
if(!vis[i])
{
int num = str[i] - 'A' + 1;
res[cnt] = str[i];
int temp = 1,cur = cnt,x = 1;
if(cnt%2 == 0) //根据第几个确定符号
temp = -1;
while(cur--)
x *= num;
cal = cal + temp * x;
cnt ++;
vis[i] = 1;
dfs(cal, cnt);
cal = cal - temp * x;
cnt --;
vis[i] = 0;
if(flag) //如果找到了就不用往下找了
return ;
}
}
}
int main()
{
while(scanf("%d%s",&target,str) != EOF)
{
if(target == 0 && !strcmp(str,"END")) break;
len = strlen(str);
memset(vis, 0 ,sizeof(vis));
flag = 0;
sort(str,str+len); //排序后从后往前找
for(int i=len-1; i>=0; i--)
{
vis[i] = 1;
int cnt = 2;
int cal = str[i] - 'A' + 1;
res[1] = str[i]; //从下标1开始存储
dfs(cal,cnt);
vis[i] = 0;
if(flag) break;
}
if(flag)
{
for(int i=1; i<6; i++)
printf("%c",res[i]);
printf("\n");
}
else
printf("no solution\n");
}
return 0;
}