题目:
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;
}