DFS(HDU 1015)

DFS(HDU 1015)

v - w^2 + x^3 - y^4 + z^5 = target


tar              str
1                ABCDEFGHIJKL
11700519  ZAYEXIWOVU
3072997    SOUGHT
1234567    THEQUICKFROG
0                END

找到 str中任意五个字符组合,使其满足v - w^2 + x^3 - y^4 + z^5 = target  的所有解中的字典序最大的那 V W X Y Z 的组合
简单DFS:
#include < iostream >
#include
< string >
#include 
< algorithm >
#include 
< cstdlib >
using   namespace  std;

char  ans[ 1000 ],str[ 20 ],res[ 20 ];
int  t,len,mark[ 20 ],flag;
int  cmp( const   void   * a, const   void   * b)
{
    
return   * ( char   * )b -* ( char   * )a;
}

bool  judge( int  v, int  w, int  x, int  y, int  z)
{
    
if (v  -  w * +  x * x * -  y * y * y * +  z * z * z * z * ==  t)
        
return   true ;
    
return   false ;
}

void  DFS( int  num)
{
    
if (flag)
        
return ;
    
if (num  ==   5 )
    {
        
if  (judge(res[ 0 ] - 64 ,res[ 1 ] - 64 ,res[ 2 ] - 64 ,res[ 3 ] - 64 ,res[ 4 ] - 64 ))
        {
            strcpy(ans,res);
            flag 
=   1 ;
        }
        
return ;
    }
    
for ( int  i = 0 ;i < len;i ++ )
    {
        
if  ( ! mark[i])
        {
            mark[i] 
=   1 ;
            res[num] 
=  str[i];
            DFS(num
+ 1 );
            mark[i] 
=   0 ;
        }
    }
}
int   main()
{
    
int  i,j,k;
    
while (scanf( " %d %s " , & t,str),strcmp(str, " END " ))
    {
        len
= strlen(str);flag = 0 ;
        qsort(str,len,
sizeof (str[ 0 ]),cmp);
        memset(mark,
0 , sizeof (mark));
        DFS(
0 );
        
if (flag)
            printf(
" %s\n " ,ans);
        
else  
            printf(
" no solution\n " );
    }
    
return   0 ;
}

你可能感兴趣的:(DFS(HDU 1015))