蓝桥杯历届-三羊献瑞
三羊献瑞
观察下面的加法算式:
(如果有对齐问题,可以参看【图1.jpg】)
其中,相同的汉字代表相同的数字,不同的汉字代表不同的数字。
请你填写“三羊献瑞”所代表的4位数字(答案唯一),不要填写任何多余内容。
C++ STL
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int s1, s2, s3, c = 0;
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
do {
if (a[0] != 0 && a[4] != 0) {
s1 = a[0]*1000+a[1]*100+a[2]*10+a[3];
s2 = a[4]*1000+a[5]*100+a[6]*10+a[1];
s3 = a[4]*10000+a[5]*1000+a[2]*100+a[1]*10+a[7];
if (s1 + s2 == s3) {
break;
}
}
c++;
}while(next_permutation(a, a+10));
printf("s3 = %d\n", s3);
printf("%d + %d = %d\n", s1, s2, s1+s2);
return 0;
}
//1085
深度搜索DFS
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int s1, s2, s3;
int a[11], book[11];
int c = 0;
bool getSum(int *a) {
if (a[0] != 0 && a[4] != 0) {
s1 = a[0]*1000+a[1]*100+a[2]*10+a[3];
s2 = a[4]*1000+a[5]*100+a[6]*10+a[1];
s3 = a[4]*10000+a[5]*1000+a[2]*100+a[1]*10+a[7];
if (s1 + s2 == s3) {
return true;
}
}
return false;
}
void dfs(int step) {
if (step == 10) {
if (getSum(a)) {
c++;
printf("s3 = %d\n", s3);
printf("%d + %d = %d\n", s1, s2, s1+s2);
exit(0); // 强制退出
}
return;
}
for (int i = 0; i < 10; i++) {
if (book[i] == 0) {
book[i] = 1;
a[step] = i;
dfs(step+1);
book[i] = 0;
}
}
}
int main() {
dfs(0);
return 0;
}
答案是1085
9567 + 1085 = 10652