USACO-Section1.3 Prime Cryptarithm [其他]

来源:互联网 发布:php 输出执行时间 编辑:程序博客网 时间:2024/06/05 11:18

2017-6-1

题目大意

下面是一个乘法竖式,如果用我们给定的那n个数字来替代*,可以使式子成立的话,我们就叫这个式子牛式。

          ***    x      **   ———————————————          ***         ***   ———————————————         ****

数字只能取代*,当然第一位不能为0,况且给定的数字里不包括0。
注意一下在美国的学校中教的“部分乘积”,第一部分乘积是第二个数的个位和第一个数的积,第二部分乘积是第二个数的十位和第一个数的乘积.
写一个程序求出所有牛式的总数。
(copy from nocow)

题解

          abc    x      de   ———————————————          ***         ***   ———————————————         ****

我们只需要枚举 abc*d,存储在partialProduct里 ,然后在两重循环枚举partialProduct,abc*d, abc*e,看它是否满足上面的竖式。

代码

/*ID: zachery1PROG: crypt1LANG: C++*/#include <iostream>#include <fstream>#include <cstring>#include <vector>#define cin fin#define cout foutusing namespace std;ifstream fin("crypt1.in");ofstream fout("crypt1.out");int n, ans = 0;bool f[10];vector<int> digits, partialProduct;int main() {    cin >> n;    memset(f, false, sizeof(f));    for (int i = 0; i < n; i++) {        int t;        cin >> t;        f[t] = true;        digits.push_back(t);    }    for (int i = 0; i < n; i++) {        for (int j = 0; j < n; j++) {            for (int k = 0; k < n; k++) {                partialProduct.clear();                for (int l = 0; l < n; l++) {                    int m = digits[l];                    int a = digits[i], b = digits[j], c = digits[k];                    int pp = (a*100 + b*10 + c) * m;                    if (pp < 100 || pp > 999) continue;                    bool flag = true;                    int t = pp;                    while (t) {                        if (!f[t%10]) {                            flag = false;                            break;                        }                        t /= 10;                    }                    if (flag) {                        partialProduct.push_back(pp);                    }                }                for (int u = 0; u < partialProduct.size(); u++) {                    for (int v = 0; v < partialProduct.size(); v++) {                        int p = partialProduct[u] + partialProduct[v]*10;                         if (p < 1000 || p > 9999) continue;                         bool flag = true;                         int t = p;                         while (t) {                             if (!f[t%10]) {                                 flag = false;                                 break;                             }                             t /= 10;                         }                         if (flag) {                             ans++;                         }                    }                }            }        }    }    cout << ans << endl;    return 0;}
原创粉丝点击