USACO 1.3.4 Prime Cryptarithm

暴力求解法,由于数据规模小,穷举即可,注意取位的技巧。

代码如下:


/*
ID: michael139
LANG: C
PROG: crypt1
*/
#include<stdio.h>
#include<string.h>
int vis[10];
int main () {
    FILE *fin  = fopen("crypt1.in", "r");
    FILE *fout = fopen("crypt1.out", "w");
    int n,i,temp,abc,de,min,max,x,y,z,p,q,mid1,mid2,ans,count;
    while (fscanf(fin,"%d",&n) != EOF) {
        count = 0;
        memset(vis,0,sizeof(vis));
        min = 10;
        max = -1;
        for (i=1;i<=n;i++) {
            fscanf(fin,"%d",&temp);
            vis[temp] = 1;
            if (min>temp) min = temp;
            if (max<temp) max = temp;
        }
        for (abc=100*min+10*min+min;abc<=100*max+10*max+max;abc++) {
            for (de=10*min+min;de<=10*max+max;de++) {
                x = abc/100;
                y = (abc - x*100)/10;
                z = abc%10;
                if (!vis[x] || !vis[y] || !vis[z]) break;
                p = de/10;
                q = de%10;
                if (!vis[p] || !vis[q]) continue;
                mid1 = q*abc;
                mid2 = p*abc;
                if (mid1+mid2*10>=10000 || mid1+mid2*10<1111) continue;
                x = mid1/100;
                y = (mid1 - x*100)/10;
                z = mid1%10;
                if (!vis[x] || !vis[y] || !vis[z]) continue;
                x = mid2/100;
                y = (mid2 - x*100)/10;
                z = mid2%10;
                if (!vis[x] || !vis[y] || !vis[z]) continue;
                ans = mid1+mid2*10;
                x = ans/1000;
                y = (ans - x*1000)/100;
                z = (ans - x*1000 - y*100)/10;
                p = ans%10;
                if (vis[x] && vis[y] && vis[z] && vis[p]) count++;
            }
        }
        fprintf(fout,"%d\n",count);
    }
    return 0;
}


你可能感兴趣的:(USACO 1.3.4 Prime Cryptarithm)