`
phinecos
  • 浏览: 342270 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

HDU1015 Safecracker

 
阅读更多

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1015

题目罗嗦了半天,其实意思很简单,就是给定一个目标值target,再给你一个备选字符串(5~12个字符),要你在这个字符串里选5个出来,满足题中给定的等式,并且你选择的这5个字符组成的字符串必须是所有可能情况中按字典序最大的情况。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

简单分析下就可以看出,就是一个组合问题,问题解的最大规模就是125,就是12*11*10*9*8*7,而最小规模是55,所以应该用枚举法就可以搞定。

#include<iostream>
#include
<string>
#include
<vector>
usingnamespacestd;

boolisOk(intv,intw,intx,inty,intz,longinttarget)
{//判断是否符合要求
if((v-w*w+x*x*x-y*y*y*y+z*z*z*z*z)==target)
returntrue;
else
returnfalse;
}

intcharToInt(charch)
{
returnch-'A'+1;
}

voidmySort(string&p,intlen)
{//让字符串按字母逆序排列,这样就可以很快找到最大符合要求的情况
inti,j;
chartemp;
for(i=0;i<len-1;i++)
{
for(j=0;j<len-i-1;j++)
{
if(p[j]<p[j+1])
{
temp
=p[j];
p[j]
=p[j+1];
p[j
+1]=temp;
}

}

}

}


intmain(intargc,char*argv[])
{
longinttarget;
inttv,tw,tx,ty,tz;
stringstrTmp;
START:
while(cin>>target>>strTmp&&!(target==0&&strTmp=="END"))
{
intlen=strTmp.length();
mySort(strTmp,len);
intv,w,x,y,z;
//下面开始用枚举法检验可能性,各个字符不能取同一个位置
for(v=0;v<len;++v)
{
for(w=0;w<len;++w)
{
if(v!=w)
{
for(x=0;x<len;++x)
{
if(x!=v&&x!=w)
{
for(y=0;y<len;++y)
{
if(y!=v&&y!=w&&y!=x)
{
for(z=0;z<len;++z)
{
if(z!=v&&z!=w&&z!=x&&z!=y)
{
tv
=charToInt(strTmp[v]);
tw
=charToInt(strTmp[w]);
tx
=charToInt(strTmp[x]);
ty
=charToInt(strTmp[y]);
tz
=charToInt(strTmp[z]);
if(isOk(tv,tw,tx,ty,tz,target))
{
cout
<<strTmp[v]<<strTmp[w]<<strTmp[x]<<strTmp[y]<<strTmp[z]<<endl;
gotoSTART;//遇到最大的符合要求的值,直接跳出,进入下一个
}

}

}

}

}

}

}

}

}

}

cout
<<"nosolution"<<endl;
}

return0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics