您的位置:首页 > 其它

usaco 1.3 Prime Cryptarithm

2012-12-07 23:03 429 查看
Prime Cryptarithm
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

题目看了半天才看懂。。。
使题目中提供的数字能够被上式所匹配即可,也就是说,将输入的数字放入规定的式子中,使式子成立。
简单模拟。

代码:

View Code

/*
ID: jings_h1
PROG: crypt1
LANG: C++
*/

#include<iostream>
#include<fstream>
using namespace std;
int n;
int a[10];
bool istrue(int b){
int k;
if(b/1000!=0){
k=1000;
// b=b%10000;
}
else{
//b=b%1000;
k=100;
}
for(;k!=0;k=k/10){
int temp=b/k;
b=b%k;
int g;
for(g=0;g<n;g++){
if(a[g]==temp)
break;
}
if(g>=n)
return false;
}
return true;
}
int main(){
ofstream fout ("crypt1.out");
ifstream fin ("crypt1.in");
int mut1[3];
int mut2[2];
fin>>n;
int sum=0;
for(int i=0;i<n;i++){
fin>>a[i];
}
for(int j1=0;j1<n;j1++){
mut1[0]=a[j1];
for(int j2=0;j2<n;j2++){
mut1[1]=a[j2];
for(int j3=0;j3<n;j3++){
mut1[2]=a[j3];
for(int j4=0;j4<n;j4++){
mut2[0]=a[j4];
for(int j5=0;j5<n;j5++){
mut2[1]=a[j5];
int temp1=mut1[0]*100+mut1[1]*10+mut1[2];
int temp2=mut2[0];
int temp3=mut2[1];
int res1=temp1*temp2;
int res2=temp1*temp3;
int res3=res1*10+res2;
if(res1/1000!=0||res2/1000!=0||res3/10000!=0)
continue;

if(istrue(res1)&&istrue(res2)&&istrue(res3)){
sum++;

}
}
}
}
}
}
fout<<sum<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: