蓝桥杯历届-三羊献瑞

蓝桥杯历届-三羊献瑞


三羊献瑞

观察下面的加法算式:

这里写图片描述
(如果有对齐问题,可以参看【图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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值