[恢]hdu 1015
2011-12-27 13:30:48
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1015
题意:在给定字符集中选5个字符(v,w,x,y,z)使得满足v - w^2 + x^3 - y^4 + z^5 = target。输出字典序最大的一个。
mark:dfs。1WA。一开始以为是字符集中序数最大的(被case2误导了)。先给字符串排一下序就好了。
代码:
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
char ans[10] ;
int visited[15] ;
char str[15] ;
int target, len ;
int dfs (int pos)
{
int i ;
// for (i = 0 ; i < pos ; i++)
// printf ("%c", ans[i]) ;
// printf ("\n") ;
if (pos == 5)
{
if ((ans[0]-'A'+1) -
(ans[1]-'A'+1)*(ans[1]-'A'+1) +
(ans[2]-'A'+1)*(ans[2]-'A'+1)*(ans[2]-'A'+1) -
(ans[3]-'A'+1)*(ans[3]-'A'+1)*(ans[3]-'A'+1)*(ans[3]-'A'+1)+
(ans[4]-'A'+1)*(ans[4]-'A'+1)*
(ans[4]-'A'+1)*(ans[4]-'A'+1)*(ans[4]-'A'+1) == target)
return 1 ;
return 0 ;
}
for (i = len-1 ; i >= 0 ; i--)
{
if (visited[i]) continue ;
ans[pos] = str[i] ;
visited[i] = 1 ;
if (dfs (pos+1))
{
visited[i] = 0 ;
return 1 ;
}
visited[i] = 0 ;
}
return 0 ;
}
int cmp(const void *a, const void *b)
{
return *(char*)a - *(char*)b ;
}
int main ()
{
while (~scanf ("%d %s%*c", &target, str) && target)
{
len = strlen (str) ;
qsort(str, len, 1, cmp) ;
if (dfs(0))
printf ("%c%c%c%c%c\n", ans[0], ans[1], ans[2], ans[3], ans[4]) ;
else
puts ("no solution") ;
}
return 0 ;
}