USACO1.3.4 Prime Cryptarithm(牛式)

来源:互联网 发布:java开源im 编辑:程序博客网 时间:2024/05/15 14:13

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 usedLine 2: N space separated digits with which to solve the cryptarithm

SAMPLE INPUT (file crypt1.in)

52 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

题目大意:以给定数字填充固定格式的竖式乘法表,求合法的方案数。

解题思路:枚举每一种可能的情况,判断其是否可行。

AC代码:

/*USER:xingwen wangTASK:crypt1LANG:C++*/#include<cstdio>int check(int k);int n,s[10];int main(){    freopen("crypt1.in","r",stdin);    freopen("crypt1.out","w",stdout);    int i,*a,*b,*c,t,*d,*e,p,q,ans=0;    scanf("%d",&n);    for(i=0;i<n;i++)    scanf("%d",&s[i]);    for(a=s;a<&s[n];a++)    for(b=s;b<&s[n];b++)    for(c=s;c<&s[n];c++)    for(d=s;d<&s[n];d++)    {           p=*c*100+*b*10+*a;           q=p**d;                      if(check(q))           {                 for(e=s;e<&s[n];e++)                 {                        t=p**e;                        if(check(t)&&check((t*10+q)/10))                        ans++;                 }                            }               }    printf("%d\n",ans);    return 0;}int check(int k){    if(k<101||k>999)    return 0;    int i=0,m,flag=0,*p;    while(++i<4)    {               m=k%10;          k/=10;              for(p=s;p<&s[n];p++)             if(m==*p)          {                 flag++;                 break;          }    }    return flag==3?1:0;}
原创粉丝点击