蛮力法/暴力法 解决基本象棋代表数字问题

兵炮马卒

在象棋版式中不同的棋子代表不同的数,如下图所示,设计一个算法求这些棋子各代表哪些数字。

QQ截图20210406155317.png

输出格式:

输出兵、炮、马、卒的取值。

输出样例1:

兵:5 炮:2 马:4 卒:0 车:1
#include<iostream>
using namespace std;

void fun(){
	for(int a=1;a<=9;a++)
		for(int b=0;b<=9;b++)
			for(int c=0;c<=9;c++)
				for(int d=0;d<=9;d++)
					for(int e=1;e<=9;e++)
					{
						if(a==b||a==c||a==d||a==e||b==c||b==e||
						c==d||c==e||d==e) continue;
						int m = a*1000+b*100+c*10+d;
						int n = a*1000+b*100+e*10+d;
						int s = e*10000+d*1000+c*100+a*10+d;
						if(s == m+n) cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<endl;
					}
}
int main(){
	fun();
	return 0;
}

 类似题目

三羊献瑞

观察下面的加法算式:
 

image.png


其中,相同的汉字代表相同的数字,不同的汉字代表不同的数字。

试确定“三羊献瑞”所代表的4位数字。

输入格式:

无输入。

输出格式:

输出“三羊献瑞”所代表的4位数字(答案唯一)。注意:4位数字间不要有空格或其他字符。

扫描二维码关注公众号,回复: 17273614 查看本文章

输入样例:无

输出样例

1085

 注意“ 气 ” -> h 也和其他数字不能相等

#include<iostream>
using namespace std;

void fun(){
	for(int a=1;a<=9;a++)
		for(int b=0;b<=9;b++)
			for(int c=0;c<=9;c++)
				for(int d=0;d<=9;d++)
					for(int e=1;e<=9;e++)
						for(int f=0;f<=9;f++)
							for(int g=0;g<=9;g++)
								for(int h=0;h<=9;h++)
									{
										if(a==b||a==c||a==d||a==e||a==f||a==g||a==h||
										b==c||b==e||b==d||b==f||b==g||b==h||
										c==d||c==e||c==f||c==g||c==h||
										d==e||d==f||d==g||d==h||
										e==f||e==g||e==h||
										f==g||f==h||
										g==h) continue;
						int m = a*1000+b*100+c*10+d;
						int n = e*1000+f*100+g*10+b;
						int s = e*10000+f*1000+c*100+b*10+h;
						if(s == m+n) cout<<e<<" "<<f<<" "<<g<<" "<<b<<endl;
					}
}
int main(){
	fun();
	return 0;
}

其他解法:

方法二:枚举2个数的各位数字
枚举"三羊献瑞"="abcd"和“三羊生瑞气”=“abfdh”,再做判定。这个方法可以减少枚举组合数量,判定条件略微复杂。

方法三:用深度优先搜索(DFS)来枚举 时间复杂度和暴力法的相同

方法四:使用置换来枚举也是一种程序代码简洁的方法。

 全排列查找

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main(){
	int a[9] = {0,2,3,4,5,6,7,8,9};
	do{
		if(a[0] >= 8){
			int ABCD = a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3];
			int EFGB = 1000 + a[4] * 100 + a[5] * 10 + a[1];
			int EFCBH = 10000 + a[4] * 1000 + a[2] * 100 + a[1] * 10 + a[6];
			if(ABCD + EFGB == EFCBH){
				cout << ABCD << " + " << EFGB << " = " << EFCBH <<endl; 
			 	cout << EFGB << endl;
			 	break;
			 }  
		}
	}while(next_permutation(a,a+9));
	return 0;
}

关于next_permutation 要使用do-while的结构的说明是:do能够执行第一次循环就满足的条件,如果第一次循环就是字典序列排序 的话将不会输出第一个排序,这里是为了保证输出结果完整,所以使用do -while .

猜你喜欢

转载自blog.csdn.net/Brittney27/article/details/134607305
今日推荐