The following cryptarithm is a multiplication problem that can be solved by substituting digits from a specified set of N digits into the positions marked with *. If the set of prime digits {2,3,5,7} is selected, the cryptarithm is called a PRIME CRYPTARITHM.
* * * x * * ------- * * * <-- partial product 1 * * * <-- partial product 2 ------- * * * *Digits can appear only in places marked by `*'. Of course, leading zeroes are not allowed.
Note that the 'partial products' are as taught in USA schools. The first partial product is the product of the final digit of the second number and the top number. The second partial product is the product of the first digit of the second number and the top number.
Write a program that will find all solutions to the cryptarithm above for any subset of digits from the set {1,2,3,4,5,6,7,8,9}.
PROGRAM NAME: crypt1
INPUT FORMAT
Line 1: | N, the number of digits that will be used |
Line 2: | N space separated digits with which to solve the cryptarithm |
SAMPLE INPUT (file crypt1.in)
5 2 3 4 6 8
OUTPUT FORMAT
A single line with the total number of unique solutions. Here is the single solution for the sample input:
2 2 2 x 2 2 ------ 4 4 4 4 4 4 --------- 4 8 8 4
SAMPLE OUTPUT (file crypt1.out)
1
S1 S4 S5 × S2 S3
如果S1×S2>10或者S1×S3>10,则3、4行肯定不是3位数,剪枝。
即S1*S2+S4*S2/10>=10 || S1*S3+S4*S3/10>=10 剪枝
补充: 从高位到低位,从小到大填数据,如果发现乘积超过999就剪枝。
/*
ID: xinming2
PROG: crypt1
LANG: C++
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <map>
#include <string>
#include <stack>
#include <ctype.h>
#include <vector>
using namespace std;
#define MAXN 20010
int a[10];
int n , ans;
void init()
{
scanf("%d",&n);
for(int i = 0 ; i < n ; i ++)
{
scanf("%d",&a[i]);
}
}
bool check(int x)//检验x中所有位的数是否都在a数组内
{
bool ok;
int j;
while(x > 0)
{
ok = false;
j = x % 10;
for(int i = 0 ; i < n ; i++)
{
if(j == a[i])ok = true;
}
if(!ok)return false;
x /= 10;
}
return true;
}
void work()
{
for(int a1 = 0 ; a1 < n ; a1++)
{
for(int a2 = 0 ; a2 < n ; a2++)
{
for(int a3 = 0 ; a3 < n ; a3++)
{
for(int b1 = 0 ; b1 < n ; b1++)
{
int s1 = a[b1] * (100 * a[a1] + 10 * a[a2] + a[a3]);
if(s1 > 999 || !check(s1))continue;
for(int b2 = 0 ; b2 < n ; b2 ++)
{
int s2 = a[b2] * (a[a1] * 100 + a[a2] * 10 + a[a3]);
if(s2 > 999 || !check(s2))continue;
int s3 = s1 + s2 * 10;
if(!check(s3))continue;
ans++;
}
}
}
}
}
}
int main()
{
freopen("crypt1.in","r",stdin);
freopen("crypt1.out","w",stdout);
init();
work();
printf("%d\n",ans);
return 0;
}
/*
*/