USACO1.3 Prime Cryptarithm(crypt1)

        采用穷举法,使用5个for循环,穷举乘数被乘数的5个数字,约束条件只有3个:1、第3行是3位数;2、第4行是3位数;3、第5行是4位数。每一种组合满足这3个条件,answer加1。

 

/*
ID:jzzlee1
PROG:crypt1
LANG:C++
*/
#include<iostream>
#include<fstream>
#include<cstring>
#include<cctype>
#include<cstdio>
using namespace std;
ifstream fin("crypt1.in");
ofstream fout("crypt1.out");
bool mark[10];
int n, a, b, num[10];
bool check(int m, int k)
{
   if (m / k > 0) return false;
   do
   {
     if (mark[m % 10] != true)
        return false;
     m /= 10;
   } while (m > 0);
   return true;
}
int main()
{   
	fin>>n;
    //cin>>n;
    for (int i = 1; i <= n; i++)
    {
		fin>>num[i];
      //cin>>num[i];
      mark[num[i]] = true;
    }
    int ans=0;
	//穷举搜索
    for (int a1 = 1; a1 <= n; a1++)
      for (int a2 = 1; a2 <= n; a2++)
        for (int a3 = 1; a3 <= n; a3++)
          for (int a4 = 1; a4 <= n; a4++)
            for (int a5 = 1; a5 <= n; a5++)    
            {
              bool flag(true);
              a = num[a1] * 100 + num[a2] * 10 + num[a3];
              if (check(a * num[a4], 1000) == false)
                 flag = false;
              if (check(a * num[a5], 1000) == false)
                 flag = false;
              b = num[a4] * 10 + num[a5];
              if (check(a * b, 10000) == false)
                 flag = false;
              if (flag) ans++;
            }
	fout<<ans<<endl;
	//cout<<ans<<endl;
	return 0;
}

你可能感兴趣的:(USACO)