蓝桥杯 15省赛 B3 三羊献瑞(暴力破解)

蓝桥杯 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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肯尼思布赖恩埃德蒙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值