hdu 1015 Safecracker 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1015
题目大意:给出一个整数、一个字符串(仅有大写字母,长度至少为5),分别定义字母A~Z的值为1~26。从字符串中取出五个字母,设其值分别为a、b、c、d、e,则如果满足a-b^2+c^3-d^4+e^5等于给出整数,则这个五字母组合就是所求答案。
题目分析:无脑暴力枚举(五重循环)就能过,我用的是dfs。先把字符串从大到小排(根据式子性质),再搜。
code:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int target,size;
char s[20],ans[6];
bool vis[20],ok;
bool cmp(char a,char b)
{
return a>b;
}
int p(char c,int x)
{
int y=1;
while(x--)
{
y*=c-'@';
}
return y;
}
bool judge()
{
int temp=0;
for(int i=1;i<6;i++)
{
temp+=p(ans[i-1],i)*(i%2?1:-1);
}
if(temp==target)return true;
else return false;
}
void dfs(int tot,int n)
{//tot指向ans,n指向s
if(tot==5)
{
if(judge())ok=true;
return;
}
if(n==size)return;
if(vis[n])dfs(tot,n+1);
else
{
ans[tot]=s[n];
vis[n]=true;
dfs(tot+1,0);
if(ok)return;
vis[n]=false;
dfs(tot,n+1);
}
}
int main()
{
while(scanf("%d %s",&target,s),target)
{
size=strlen(s);
memset(vis,false,sizeof(vis));
ok=false;
sort(s,s+strlen(s),cmp);
dfs(0,0);
printf("%s\n",ok?ans:"no solution");
}
return 0;
}
PS:搜索不加剪枝,跟暴力枚举有什么区别?!居然还过了,说明数据比较水。
PSS:最近做了几道非图搜索,这道题是冲着dfs来的,理解起来不难,要自己写,还有一段距离……