[关键字]:搜索
[题目大意]:给出一个形如ABCDE+DACEB=BC的式子,每个字母代表一个数字,求出可能的方案有多少。
//=====================================================================================================================================================
[分析]:虫食算的超级简化版……只有5个字母,暴力搜索就可以过……注意不要忽略细节:除数不能为0,判断除法是否成立最好用乘法判断……
[代码]:
View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
char s[4][10];
int b[10],d[10],a[4];
int test,ans;
bool v[10];
void Cleck()
{
memset(a,0,sizeof(a));
for (int i=1;i<=3;i++)
{
int len=strlen(s[i]);
for (int j=0;j<len;j++)
a[i]=a[i]*10+d[s[i][j]-'A'];
}
//printf("%d %d %d\n",a[1],a[2],a[3]);
//printf("%d %d %d %d %d\n",d[0],d[1],d[2],d[3],d[4]);
//system("pause");
if (a[1]+a[2]==a[3]) ans++/*,printf("%d+%d=%d\n",a[1],a[2],a[3])*/;
if (a[1]-a[2]==a[3]) ans++/*,printf("%d-%d=%d\n",a[1],a[2],a[3])*/;
if (a[1]*a[2]==a[3]) ans++/*,printf("%d*%d=%d\n",a[1],a[2],a[3])*/;
if (a[3]*a[2]==a[1] && a[2]!=0) ans++/*,printf("%d/%d=%d\n",a[1],a[2],a[3])*/;
}
void Dfs(int k)
{
if (k==5)
{
Cleck();
return ;
}
if (!b[k]) {Dfs(k+1);return ;}
for (int i=(b[k]==1)?0:1;i<=9;i++)
if (v[i]) v[i]=0,d[k]=i,Dfs(k+1),v[i]=1;
}
int main()
{
freopen("out.txt","w",stdout);
scanf("%d",&test);
while (test--)
{
memset(b,0,sizeof(b));
memset(v,1,sizeof(v));
ans=0;
scanf("%s",s[1]);
//printf("%s\n",s[1]);
scanf("%s",s[2]);
//printf("%s\n",s[2]);
scanf("%s",s[3]);
//printf("%s\n",s[3]);
for (int i=1;i<=3;i++)
{
int len=strlen(s[i]);
for (int j=0;j<len;j++) if (!b[s[i][j]-'A']) b[s[i][j]-'A']=1;
if (len>1) b[s[i][0]-'A']=2;
}
//printf("%s\n",s[3]);
//printf("%d %d %d %d %d\n",b[0],b[1],b[2],b[3],b[4]);
Dfs(0);
printf("%d\n",ans);
}
return 0;
}