原题:
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.
The partial products must be three digits long, even though the general case (see below) might have four digit partial products.
** Note About Cryptarithm’s Multiplication ****
In USA, children are taught to perform multidigit multiplication as described here. Consider multiplying a three digit number whose digits are ‘a’, ‘b’, and ‘c’ by a two digit number whose digits are ‘d’ and ‘e’:
[Note that this diagram shows far more digits in its results than
the required diagram above which has three digit partial products!]
a b c <-- number 'abc'
x d e <-- number 'de'; the 'x' means 'multiply'
-----------
p1 * * * * <– product of e * abc; first star might be 0 (absent)
p2 * * * * <– product of d * abc; first star might be 0 (absent)
———–
* * * * * <– sum of p1 and p2 (e*abc + 10*d*abc) == de*abc
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 supplied non-zero single-digits.
题意:
用给定的n个数字(每个可以重复使用)往算式里面填,看有多少满足的方案。
题解:
暴力枚举所有三位数*两位数,然后在枚举中加判断和剪枝。
直接上代码:
/*
ID:newyear111
PROG: crypt1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>
using namespace std;
const int N=15;
int hash[N];
int n;
bool isOK(int x){
while(x){
if(!hash[x%10]){
return 0;
}
x/=10;
}
return 1;
}
int main()
{
ifstream fin("crypt1.in");
ofstream fout("crypt1.out");
fin>>n;
for(int i=0;i<n;i++){
int t;
fin>>t;
hash[t]=1;
}
int ans=0;
for(int i=100;i<=999;i++){
if(isOK(i)){
for(int j=10;j<=99;j++){
if(isOK(j)){
int t=i*j;
int t1=i*(j%10);
int t2=i*(j/10);
//剪枝
if(t>9999)
break;
if(t1>999||t1<100||t2>999||t2<100||t<1000)
continue;
if(isOK(t)&&isOK(t1)&&isOK(t2))
ans++;
}
}
}
}
fout<<ans<<endl;
fin.close();
fout.close();
return 0;
}