用深搜写排列,除法要注意,还有不能有前导零。当然可以5个for,但是如果有很多个,dfs还是好的。
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<map> 5 #define mt(a,b) memset(a,b,sizeof(a)) 6 using namespace std; 7 const int M=16; 8 char sa[M],sb[M],sc[M],ha[M],hb[M],op[]="+-*/"; 9 int val[8]; 10 bool use[16]; 11 map<string,bool> mp; 12 string str; 13 bool prezero(char s[]){ 14 if(strlen(s)>1&&!val[s[0]-'A']) return true; return false; 15 } 16 int getint(char s[]){ 17 int res=0; 18 for(int i=0;s[i];i++){ 19 res=(res<<3)+(res<<1)+val[s[i]-'A']; 20 } 21 return res; 22 } 23 int solve(const int &a,const char &ope,const int &b){ 24 if(ope=='+') return a+b; 25 if(ope=='-') return a-b; 26 if(ope=='*') return a*b; 27 if(b&&!(a%b))return a/b; 28 return -1; 29 } 30 void flag(const int &a,const char &ope,const int &b){ 31 sprintf(ha,"%d",a); 32 sprintf(hb,"%d",b); 33 str=(string)ha+ope+(string)hb; 34 mp[str]=true; 35 } 36 void dfs(int t){ 37 if(t==5){ 38 if(prezero(sa)||prezero(sb)||prezero(sc)) return ; 39 int a=getint(sa); 40 int b=getint(sb); 41 int c=getint(sc); 42 for(int i=0;i<4;i++){ 43 if(solve(a,op[i],b)==c){ 44 flag(a,op[i],b); 45 } 46 } 47 return ; 48 } 49 for(int i=0;i<10;i++){ 50 if(!use[i]){ 51 val[t]=i; 52 use[i]=true; 53 dfs(t+1); 54 use[i]=false; 55 } 56 } 57 } 58 int main(){ 59 int t; 60 while(~scanf("%d",&t)){ 61 while(t--){ 62 scanf("%s%s%s",sa,sb,sc); 63 mt(use,0); 64 mp.clear(); 65 dfs(0); 66 printf("%d\n",mp.size()); 67 } 68 } 69 return 0; 70 }