USACO Prime Cryptarithm


Prime Cryptarithm

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

SAMPLE INPUT (file crypt1.in)

5
2 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


Submission file Name:   
USACO Gateway  |    Comment or Question


/*
    ID:qhn9992
    PROG:crypt1
    LANG:C++11
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

int a[12],n,n4[2000],n2[200],c4=0,c2=0,ans=0,vis[12];

void get_n4()
{
	for(int i=0;i<n;i++)
	{
		if(a[i]==0) continue;
		for(int j=0;j<n;j++)
		{
			for(int k=0;k<n;k++)
			{
				int t=a[i]*100+a[j]*10+a[k];
				n4[c4++]=t;
			}
		}
	}
}

void get_n2()
{
	for(int i=0;i<n;i++)
	{
		if(a[i]==0) continue;
		for(int j=0;j<n;j++)
		{
			int t=a[i]*10+a[j];
			n2[c2++]=t;
		}
	}
}

int getwei(int x)
{
	return floor(log(x+0.0)/log(10.))+1;
}

bool ck2(int x)
{
	if(x==0)  return vis[0];
	while(x)
	{
		int t=x%10;
		x/=10;
		if(!vis[t]) return false;
	}
	return true;
}

void ck()
{
	for(int i=0;i<c4;i++)
	{
		for(int j=0;j<c2;j++)
		{
			int part1=n4[i]*(n2[j]%10);
			int part2=n4[i]*(n2[j]/10);
			int last=n4[i]*n2[j];

			if(getwei(part1)==3 && getwei(part2)==3 && getwei(last)==4)
			{
				if(ck2(part1)&&ck2(part2)&&ck2(last)) ans++;
			}
		}
	}
}

int main()
{
    freopen("crypt1.in","r",stdin);
    freopen("crypt1.out","w",stdout);
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",a+i);
		vis[a[i]]=1;
	}
	sort(a,a+n);
	get_n4(); get_n2();
	ck();
	printf("%d\n",ans);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值