就是对各种情况进行模拟,dfs实现。一定要注意被除数不可以为0
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
map<char,int> fir;
map<char,int> to;
char s1[10],s2[10],s3[10];
char s[10];
int len,len1,len2,len3;
int ans;
int vis[10];
bool check( )
{
int num1 = 0,num2 = 0,num3 = 0;
for ( int i=0; i<len1; i++ )
num1 = num1*10 + to[s1[i]];
for ( int i=0; i<len2; i++ )
num2 = num2*10 + to[s2[i]];
for ( int i=0; i<len3; i++ )
num3 = num3*10 + to[s3[i]];
if ( num1+num2==num3 ) ++ans;
if ( num1*num2==num3 ) ++ans;
if ( num1 && num2 && num1/num2==num3 && num1%num2==0 ) ++ans;
if ( num1-num2==num3 ) ++ans;
}
void dfs ( int step )
{
// cout<<"len "<<len<<" step " <<step<<endl ;
if ( step>=len ) {
check();
return ;
}
for ( int i=0; i<10; i++ ) {
if ( !vis[i] ) {
if ( i==0 && fir.count(s[step]) ) continue;
vis[i] = 1 ;
to[s[step]] = i;
dfs( step+1 ) ;
vis[i] = 0 ;
}
}
}
int main()
{
int t;
cin>>t;
while ( t-- )
{
scanf(" %s %s %s",&s1,&s2,&s3);
fir.clear();
to.clear();
memset( vis,0,sizeof vis );
len = 0 ;
len1 = strlen( s1 );
len2 = strlen( s2 );
len3 = strlen( s3 );
if ( len1>1 ) fir[s1[0]]++;
if ( len2>1 ) fir[s2[0]]++;
if ( len3>1 ) fir[s3[0]]++;
for ( int i=0; i<len1; i++ ) if ( !to.count(s1[i]) ) to[s1[i]] = 1,s[len++] = s1[i];
for ( int i=0; i<len2; i++ ) if ( !to.count(s2[i]) ) to[s2[i]] = 1,s[len++] = s2[i];
for ( int i=0; i<len3; i++ ) if ( !to.count(s3[i]) ) to[s3[i]] = 1,s[len++] = s3[i];
s[len] = '\0';
ans = 0 ;
dfs( 0 ) ;
cout<<ans<<endl ;
}
return 0;
}