Forming a Magic Square

题目:

We define a magic square to be an  matrix of distinct positive integers from  to  where the sum of any row, column, or diagonal (of length ) is always equal to the same number (i.e., the magic constant).

Consider a  matrix, , of integers in the inclusive range . We can convert any digit, , to any other digit, , in the range  at cost .

Given , convert it into a magic square at minimal cost by changing zero or more of its digits. Then print this cost on a new line.

大意:输入一个3阶矩阵,把它调整为幻方,并且调整的cost最小,求这个最小的cost。cost定义,比如在a[0][0]这个位置的数,从2变为了3,cost=|3-2| = 1

额外的知识:对于n阶,幻方的和为 n*(n^2+1)/2


思路:把3阶的8个幻方情况列举出来,作为查询表,依次比较哪个的cost最小

#include <bits/stdc++.h>

using namespace std;
int magic_mat[8][3][3] = {
    {{8, 1, 6}, {3, 5, 7}, {4, 9, 2}},
    {{6, 1, 8}, {7, 5, 3}, {2, 9, 4}},
    {{4, 9, 2}, {3, 5, 7}, {8, 1, 6}},
    {{2, 9, 4}, {7, 5, 3}, {6, 1, 8}}, 
    {{8, 3, 4}, {1, 5, 9}, {6, 7, 2}}, 
    {{4, 3, 8}, {9, 5, 1}, {2, 7, 6}}, 
    {{6, 7, 2}, {1, 5, 9}, {8, 3, 4}}, 
    {{2, 7, 6}, {9, 5, 1}, {4, 3, 8}},  
};

int main() {
    vector< vector<int> > s(3,vector<int>(3));
    for(int s_i = 0;s_i < 3;s_i++){
       for(int s_j = 0;s_j < 3;s_j++){
          cin >> s[s_i][s_j];
       }
    }
    //  Print the minimum cost of converting 's' into a magic square
    int min = 100;
    for(int k=0;k<8;k++)
    {
        int cost = 0;;
        for(int i =0;i<3;i++)
        {
            for(int j =0;j<3;++j)
            {
                cost += abs(s[i][j] - magic_mat[k][i][j]);
            }
        }
        if(cost <min)
            min = cost;
    }
    cout <<min<<endl;
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值