USACO Prime Cryptarithm

思路 : 枚举,第一个乘数是三位数,所以枚举100~1000;第二个数是两位数,枚举10~100以内的数。然后要解决的一个问题是如何判断这些数的每一位都是输入的数。这里有一个小技巧:建一个num[10]数组,如果对于每一个输入的数,num[i]设为1,否知设为0。这样的话,我们在判断每一位是否是符合要求时只要看一看num[i]是否为1就可以了!

下面是代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#define N 10

using namespace std;

int num[N];
bool isfit( int n, int bit )
{
    while( bit-- )
    {
        if( !num[n%10] )
        {
            //cout << "bit = "<< bit << endl;
            return false;
        }
        n /= 10;
    }
    return n == 0 ? true : false;
}

bool solve( int p1, int p2 )
{
    if( !isfit( p1, 3 ) || !isfit( p2, 2 ) )
    {
        return false;
    }
    if( !isfit( p1 * ( p2%10 ), 3 ) || !isfit( p1 * ( p2/10 ), 3 ) || !isfit( p1 * p2, 4 ) )
    {
        return false;
    }
    return true;
}

int main()
{
    freopen( "crypt1.in", "r", stdin );
    freopen( "crypt1.out", "w", stdout );
    int n;
    memset( num, 0, sizeof( num ) );
    int t;
    int ans = 0;
    while( cin >> n )
    {
        for( int i = 0; i < n; i++ )
        {
            cin >> t;
            num[t] = 1;
        }
        for( int i = 100; i < 1000; i++ )
        {
            for( int j = 10; j < 100; j++ )
            {
                if( solve( i, j ) )
                {
                    ans++;
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011564456/article/details/23124217