ConstStar
发布于 2022-09-04 / 121 阅读 / 0 评论 / 0 点赞

蓝桥杯2013年C组:幻方填空

题目描述

幻方是把一些数字填写在方阵中,使得行、列、两条对角线的数字之和都相等。
欧洲最著名的幻方是德国数学家、画家迪勒创作的版画《忧郁》中给出的一个4阶幻方。
他把1,2,3,...16 这16个数字填写在4 x 4的方格中。
如图p1.jpg所示,即:

16 ?  ?  13
?  ?  11 ?
9  ?  ?  *
?  15 ?  1

表中有些数字已经显露出来,还有些用?和*代替。
请你计算出? 和 * 所代表的数字。并把 * 所代表的数字作为本题答案提交。

解决方案

思路

全排列

代码

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;


int main() {

    // 1 9 11 13 15 16
    vector<int> list = {2, 3, 4, 5, 6, 7, 8, 10, 12, 14};

    do {
        int a1 = 16 + list[0] + list[1] + 13;
        int a2 = list[2] + list[3] + 11 + list[4];
        int a3 = 9 + list[5] + list[6] + list[7];
        int a4 = list[8] + 15 + list[9] + 1;


        int b1 = 16 + list[2] + 9 + list[8];
        int b2 = list[0] + list[3] + list[5] + 15;
        int b3 = list[1] + 11 + list[6] + list[9];
        int b4 = 13 + list[4] + list[7] + 1;

        int c1 = 16 + list[3] + list[6] + 1;
        int c2 = 13 + 11 + list[5] + list[8];

        if (a1 == a2 && a2 == a3 && a3 == a4 && a4 == b1 && b1 == b2 && b2 == b3 && b3 == b4 && b4 == b1 && c1 == c2) {
            cout << list[7];
        }
    } while (next_permutation(list.begin(), list.end()));

    return 0;
}

输出

12


评论