蓝桥杯 15省赛 B3 三羊献瑞(暴力破解)
三羊献瑞
观察下面的加法算式:
其中,相同的汉字代表相同的数字,不同的汉字代表不同的数字。
思路:
只要可以暴力破解(数据规模不是很大),代码又臭又长但又何妨
public class 细节_3 {
public static void main(String[] args) {
//外8层的循环变量必须为0,不然没结果
for(int a =0 ;a <10 ;a ++) {
for(int b =0 ;b <10 ;b ++) {
for(int c =0 ;c <10 ;c ++) {
for(int d =0 ;d <10 ;d ++) {
for(int e =0 ;e <10 ;e ++) {
for(int f =0 ;f <10 ;f ++) {
for(int g =0 ;g <10 ;g ++) {
for(int h =0 ;h <10 ;h ++) {
int[] arr = {a ,b ,c ,d ,e ,f ,g ,h};
boolean[] flag =new boolean[10];
for(int i :arr) {
flag[i] =!flag[i];
}
int temp =0;
for(boolean bool :flag) {
if(!bool) {
temp ++;
}
}
if(temp !=2) {
continue;
}
//每个数开头不能是'0'
if(arr[4] ==0 ||arr[0] ==0) {
continue;
}
int y =Integer.parseInt(arr[4]+""+arr[5]+""+arr[6]+""+arr[1]);
int z =Integer.parseInt(arr[4]+""+arr[5]+""+arr[2]+""+arr[1]+""+arr[7]);
int x =Integer.parseInt(arr[0]+""+arr[1]+""+arr[2]+""+arr[3]);
if(x +y !=z) {
continue;
}
System.out.println("x"+x+"y"+y+"z"+z);
}
}
}
}
}
}
}
}
}
}
深搜的做法
//[1, 0, 6, 5, 2, 8, 9, 7]
//x9567y1085z10652
public class Test {
static int[] a =new int[8];
static boolean[] b =new boolean[10];
public static void main(String[] args) {
for(int i =0 ;i <a.length ;i ++) a[i] =-1; //去'0'
dfs(0);
System.out.println(Arrays.toString(a));
}
private static boolean dfs(int lev) {
if(lev ==8) {
int x =a[6] *1000 +a[3] *100 +a[2] *10 +a[7];
int y =a[0] *1000 +a[1] *100 +a[5] *10 +a[3];
int z =a[0] *10000 +a[1] *1000 +a[2] *100 +a[3] *10 +a[4];
if(z ==x +y) return true; else return false;
}
for(int i =0 ;i <=9 ;i ++) {
if(lev ==0 &&i ==0) continue; //第一位不能是'0'
if(b[i]) continue;
b[i] =true;
a[lev] =i;
if(dfs(lev +1)) return true;
b[i] =false;
a[lev] =-1;
}
return false;
}
}