首页 > USACO题解 > USACO Prime Cryptarithm

USACO Prime Cryptarithm

先产生所有能的三位数和两位数,然后两层循环枚举所有可能的情况,判断是否符合条件即可。

/*
	ID:stackex1
	LANG:C
	PROG:crypt1
*/
#include <stdio.h>

int checkok(int num, int digit[], int n)
{
	int i;
	if(!(num >= 100 && num <= 999))
		return 0;
	while(num)
	{
		for(i = 0; i < n; ++i)
		{
			if(num%10 == digit[i]) break;
		}
		if(i == n) return 0;
		num /= 10;
	}
	return 1;
}

int checkok2(int num, int digit[], int n)
{
	int i;
	if(!(num >= 1000 && num <= 9999))
		return 0;
	while(num)
	{
		for(i = 0; i < n; ++i)
		{
			if(num%10 == digit[i]) break;
		}
		if(i == n) return 0;
		num /= 10;
	}
	return 1;
}

int main(int argc, char **argv)
{
	FILE *fin = fopen("crypt1.in", "r");
	FILE *fout = fopen("crypt1.out", "w");
	
	int n, i, j, k, tmp, res;
	int digit[10] = {0};
	int up[1000], down[100];
	int upnum, downnum;
	
	fscanf(fin, "%d", &n);
	for(i = 0; i < n; ++i)
	{
		fscanf(fin, "%d", &digit[i]);
	}
	/*产生所有可能的数字*/
	upnum = downnum = 0;
	for(i = 0; i < n; ++i)
	{
		for(j = 0; j < n; ++j)
		{
			tmp = digit[i]*10 + digit[j];
			down[downnum++] = tmp;
			for(k = 0; k < n; ++k)
			{
				tmp = digit[i]*100 + digit[j]*10 + digit[k];
				up[upnum++] = tmp;
			}
		}
	}
	/*判断数字是否符合要求*/
	res = 0;
	for(i = 0; i < upnum; ++i)
	{
		for(j = 0; j < downnum; ++j)
		{
			if(checkok(up[i]*(down[j]%10), digit, n) && checkok(up[i]*(down[j]/10), digit, n))
			{
				tmp = up[i] * down[j];
				if(checkok2(tmp, digit, n)) ++res;
			}
		}
	}
	fprintf(fout, "%d\n", res);
	fclose(fin);
	fclose(fout);
	
	return 0;
}

觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> USACO Prime Cryptarithm
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



分类: USACO题解 标签: ,
  1. 本文目前尚无任何评论.