USACO Prime Cryptarithm

1、这题很怪,刚开始数组s开成5就一直是运行错,开成6就没问题了。。。

2、暴力法,很简单。

/*
ID:mrxy564
PROG:crypt1
LANG:C++
*/
#include<cstdio>
#include<cstring>
using namespace std;
int cnt,in[10];
bool is_valid(int num,int bit){
    char s[6];
    sprintf(s,"%d",num);
    if(s[0]=='0') return false;
    int len=strlen(s);
    if(len!=bit) return false;
    for(int i=0;i<len;i++)
       if(!in[s[i]-'0']) return false;
    return true;
}
int main(){
    freopen("crypt1.in","r",stdin);
    freopen("crypt1.out","w",stdout);
    int num,temp,a,b;
    scanf("%d",&num);
    memset(in,0,sizeof(in));
    for(int i=0;i<num;i++){
       scanf("%d",&temp);
       in[temp]=1;
    }
    for(int i=100;i<=999;i++){
      if(is_valid(i,3)){
       for(int j=10;j<=99;j++){
           if(is_valid(j,2)){
             if(is_valid(j/10*i,3)&&is_valid(j%10*i,3)&&is_valid(i*j,4)){
                  cnt++;
             }
           }
       }
      }
    }
    printf("%d\n",cnt);
}
官方题解:

The constraints of this problem are small enough that we can just try all possible products of 3 digit * 2 digit numbers, and look to see if all the correct digits are used.

The function "isgood" checks that a number is composed only of acceptable digits, and "isgoodprod" checks that all the lines of the multiplication are composed of acceptable digits.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

int isgooddigit[10];	/* isgooddigit[d] is set if d is an acceptable digit
*/

/* check that every decimal digit in "n" is a good digit,
   and that it has the right number "d" of digits. */
int
isgood(int n, int d)
{
    if(n == 0)
		return 0;

    while(n) {
	if(!isgooddigit[n%10])
	    return 0;
	n /= 10;
        d--;
    }

    if( d == 0 )
       return 1;
    else
       return 0;
}

/* check that every product line in n * m is an okay number */
int
isgoodprod(int n, int m)
{
    if(!isgood(n,3) || !isgood(m,2) || !isgood(n*m,4))
	return 0;

    while(m) {
	if(!isgood(n*(m%10),3))
	    return 0;
	m /= 10;
    }
    return 1;
}

void
main(void)
{
    int i, j, n, nfound;
    FILE *fin, *fout;

    fin = fopen("crypt1.in", "r");
    fout = fopen("crypt1.out", "w");
    assert(fin != NULL && fout != NULL);

    for(i=0; i<10; i++) {
        isgooddigit[i] = 0;
    }
    fscanf(fin, "%d", &n);
    for(i=0; i<n; i++) {
	fscanf(fin, "%d", &j);
	isgooddigit[j] = 1;
    }

   nfound = 0;
   for(i=100; i<1000; i++)
	for(j=10; j<100; j++)
	    if(isgoodprod(i, j))
		nfound++;

   fprintf(fout, "%d\n", nfound);
   exit(0);
}



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值