USACO Section 1.3 Prime Cryptarithm

题目描述

下面的算术是一个乘法问题,可以通过将数字从指定的N位数字替换到标有*的位置来解决。 如果选择了一组素数{2,3,5,7},则将该算法称为PRIME CRYPTARITHM。
       * * *
      X  * *
      -------
       * * * < - 部分产品1
      * * * < - 部分产品2
      -------
      * * * *
数字只能在“*”标记的地方出现。 当然,不允许前导零。
部分产品必须是三位数字,即使一般情况(见下文)可能有四位数部分产品。

**********关于加密乘法的注意事项************
在美国,孩子被教导执行多位数乘法,如这里所述。考虑将数字为“a”,“b”和“c”的三位数乘以数字为“d”和“e”的两位数字:
[请注意,该图表显示的结果比数字多得多
所需的图上面有三位数部分产品!]
          a b c < - number'abc'
         x  d e < - number'de'; 'x'表示“乘”
        -----------
       p1 * * * * < - e * abc的乘积第一颗星星可能是0(缺席)
      p2 * * * * < - d * abc的乘积第一颗星星可能是0(缺席)
       -----------
        * * * * * < - p1和p2的和(e * abc + 10 * d * abc)== de * abc
请注意,“部分产品”在美国学校教授。第一部分产品是第二个数字的最终数字和最大数字的乘积。第二部分产品是第二个数字的第一位数字和最大数字的乘积。


编写一个程序,找到所提供的非零单个数字子集的所有解决方案。

程序名称:crypt1
输入格式

行1:N,将被使用的位数
第2行:N个空格分隔的非零数字用于解决cryptarithm

输入 (file crypt1.in)

 
 
5
2 3 4 6 8

输出格式

一行与解决方案的总数。 以下是样本输入的单一解决方案:
       2 2 2
      x  2 2
      ------
       4 4 4
      4 4 4
     ---------
      4 8 8 4

输出(file crypt1.out)
1

解题思路

本题主要思路为,对输入的5个数进行全排列,分别为a,b,c,d,e。p=(100*x[1]+10*x[2]+x[3])*x[5],q=(100*x[1]+10*x[2]+x[3])*x[4],r=10*q+p。然后判断p,q是否为3位数,r是否为4位数。是的话总数加一。

解题代码

/*
ID: 15189822
PROG: crypt1
LANG: C++
*/
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
ifstream fin("crypt1.in");
ofstream fout("crypt1.out");
bool f[10];
int x[10],j,sum=0,p,q,r;
int cal1(int n){
    int r=0;
    while (n){
        r++;
        n/=10;
    }
    return r;
}
bool cal2(int n){
    while (n){
        if (!f[n%10]) return false;
        n/=10;
    }
    return true;
}
bool res(){
    p=(100*x[1]+10*x[2]+x[3])*x[5];
    q=(100*x[1]+10*x[2]+x[3])*x[4];
    r=10*q+p;
    if (cal1(p)==3&&cal2(p)&&cal1(q)==3&&cal2(q)&&cal1(r)==4&&cal2(r)) return true;
    return false;
}
void dfs(int step){
    if (step==6){
        if (res()){
            sum++;
        }
        return ;
    }
    for (int i=1;i<=9;i++){
        if (f[i]){
            x[step]=i;
            dfs(step+1);
        }
    }
}
int main(){
    int n,m;
    j=0;
    fin>>n;
    memset(f,false,sizeof(f));
    memset(x,0,sizeof(x));
    for (int i=1;i<=n;i++){
        fin>>m;
        f[m]=true;
    }
    dfs(1);
    fout<<sum<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/YanLucyqi/article/details/77162873