Simple depth-first search. To find the maximum dictionary order, note the first order.
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intSize= -;Chara[5];intvis[size*2+Ten];BOOLcmpCharACharb) { returnB >A;}intNpow (intXintN) { intres=1; while(n) {if(n&1) res*=x; X*=x; N>>=1; } returnRes;}BOOLCheckLong Longtarget) { Long Longans=0; for(intI=0;i<5; i++) { if((i+1)%2==1) ans+=npow (a[i]-'A'+1, i+1); Elseans-=npow (a[i]-'A'+1, i+1); } if(ans==target)return true; return false;}Char out[6];voidDfsintICharOp[],Long Longtarget) { if(i==5) { if(check (target)) { for(intj=0;j<5; j + +) out[j]=A[j]; } return ; } for(intj=0; op[j];j++) { intit=op[j]-'A'+1; if(!Vis[it]) {Vis[it]=1; A[i]=Op[j]; DFS (i+1, Op,target); Vis[it]=0; A[i]=' /'; } }}intMain () {Long LongTarget; Charop[size]={' /'}; while(SCANF ("%lld%s", &target,&op)!=eof&&target!=0&&STRCMP (OP,"END")!=0) {sort (Op,op+strlen (OP), CMP); memset ( out,' /',sizeof( out)); Memset (A,' /',sizeof(a)); DFS (0, Op,target); if( out[0]==' /') printf ("No solution\n"); Elseprintf ("%s\n", out); Memset (OP,' /',sizeof(OP)); } return 0;}
HDOJ1015 (Simple deep Search)