USACO-Section1.4 Prime Cryptarithm (搜索)

2017-5-27

题目描述

给你几个数字,求出给定等式中数字都在这几个数中的数的个数

解答

深搜,深度只要到5即可

代码

/*
ID: 18795871
PROG: crypt1
LANG: C++
*/
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;

ifstream fin("crypt1.in");
ofstream fout("crypt1.out");

bool f[10];
int x[10],j,sum=0,p,q,r;

int cal1(int n){
    int r=0;
    while (n){
        r++;
        n/=10;
    }
    return r;
}

bool cal2(int n){
    while (n){
        if (!f[n%10]) return false;
        n/=10;
    }
    return true;
}

bool res(){
    p=(100*x[1]+10*x[2]+x[3])*x[5];
    q=(100*x[1]+10*x[2]+x[3])*x[4];
    r=10*q+p;
    if (cal1(p)==3&&cal2(p)&&cal1(q)==3&&cal2(q)&&cal1(r)==4&&cal2(r)) return true;
    return false;
}

void dfs(int step){
    if (step==6){
        if (res()){
            sum++;
        }
        return ;
    }
    for (int i=1;i<=9;i++){
        if (f[i]){
            x[step]=i;
            dfs(step+1);
        }
    }
}

int main()
{
    int n,m;
    j=0;
    fin>>n;
    memset(f,false,sizeof(f));
    memset(x,0,sizeof(x));
    for (int i=1;i<=n;i++){
        fin>>m;
        f[m]=true;
    }
    dfs(1);
    fout<<sum<<endl;
    return 0;
}

简单的搜索题吧!只要把所有的情况找出来然后再判断是否符合题意即可。

/*
ID: 18795871
PROG: crypt1
LANG: C++
*/
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;

ifstream fin("crypt1.in");
ofstream fout("crypt1.out");

const int N = 10;
bool f[N+1];
int x[5],cnt;

bool jud(int n,int l){
    int num=0;
    while (n){
        if (!f[n%10]) return false;
        n/=10;
        num++; 
    }
    if (num>l) return false;
    return true;
}

bool isOK(){
    int p=(100*x[0]+10*x[1]+x[2])*x[4];
    int q=(100*x[0]+10*x[1]+x[2])*x[3];
    if (jud(p,3)&&jud(q,3)&&jud(p+q*10,4)) return true;
    return false;
}

void dfs(int step){
    if (step==5){
        if (isOK()){
            cnt++;
        }
        return ;
    }
    for (int i=0;i<N;i++){
        if (f[i]){
            x[step]=i;
            dfs(step+1);
        }
    }
}

int main(){
    int n,t;
    while (fin>>n){
        cnt=0;
        memset(f,false,sizeof(f));
        for (int i=0;i<n;i++){
            fin>>t;
            f[t]=true;
        }
        dfs(0);
        fout<<cnt<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值