蓝桥杯--三羊献瑞

观察下面的加法算式:

       祥 瑞 生 辉
  +   三 羊 献 瑞
-------------------
   三 羊 生 瑞 气

(如果有对齐问题,可以参看【图1.jpg】)

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

请你填写“三羊献瑞”所代表的4位数字(答案唯一),不要填写任何多余内容。
------------------------------------------------
 分析:简单的暴力枚举。注意题意:
           1.不同的汉字代表不同的数字。所以得出的 ‘气’ 字应与所枚举的数字不同
           2. 答案唯一。经过测试,当" 祥 瑞 生 辉"为以零开头的三位数字时 或 “三 羊 献 瑞” 是以零开头的三位数字时,答案并不唯一。
                                 故他们有应以1开头枚举。
运行结果:1085
-------------------------------------------------
#include<iostream>
#define For(x) for(int x = 0; x <= 9; x++)
using namespace std;
int main(){
    int a,b,c,d,e,f,g;
    int temp1,temp2,temp3;
    for(int a = 1; a <= 9; a++){
    For(b){
    For(c){
    For(d){
    for(int e = 1; e <= 9; e++){
    For(f){
    For(g){
        if(a!=b&&a!=c&&a!=d&&a!=e&&a!=f&&a!=g&&b!=c&&b!=d&&b!=e&&b!=f&&b!=g
           &&c!=d&&c!=e&&c!=f&&c!=g&&d!=e&&d!=f&&d!=g&&e!=f&&e!=g&&f!=g){
            temp1 = a*1000 + b*100 + c*10 + d;
            temp2 = e*1000 + f*100 + g*10 + b;
            temp3 = temp1 + temp2;
            if(temp3%10!=a&&temp3%10!=b&&temp3%10!=c&&temp3%10!=d&&temp3%10!=e&&temp3%10!=f&&temp3%10!=g
               &&(temp3/10)%10==b && (temp3/100)%10==c && (temp3/1000)%10==f && (temp3/10000)==e){
                cout<<temp2<<endl;
               }
            
           }
    }}}}}}}             
    return 0;
}

-----------------------------------------
用STL的next_permutation();解法:
定义一个数组int a[10],初始化用a[i]存储i。将a[2]~a[9]与各个汉字对应,然后用next_permutation全排列暴力解,注意三个数值开头不能为0,能解出第2个数值。
#include <cstdio>
 #include <algorithm>
using namespace std;

int main() {
    int a[10];
    for (int i = 0; i < 10; i++) a[i] = i;

    do {
        if (!a[2] || !a[6]) continue;
        int x =              a[2]*1000 + a[3]*100 + a[4]*10 + a[5];
        int y =              a[6]*1000 + a[7]*100 + a[8]*10 + a[3];
        int z = a[6]*10000 + a[7]*1000 + a[4]*100 + a[3]*10 + a[9];
        if (x + y == z) printf("%d + %d = %d\n", x, y, z);
    } while (next_permutation(a, a+10));

    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值