Study/PS(Algorithm)
[C++] HackerRank 해커랭크 Forming a Magic Square
노랑펭귄
2018. 3. 14. 05:53
문제링크 : https://www.hackerrank.com/challenges/magic-square-forming
전형적인 마방진 알고리즘 문제다.
특별할 것은 없고 주어진 조건에 따라서 마방진을 만들 수 있는 모든 경우의 수를 구한 다음 일일이 대조시키는 방식으로 풀었다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #include <bits/stdc++.h> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ // input numbers int s[3][3]; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) cin >> s[i][j]; int ans[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 min_cost = 100; int calc = 0; for(int n = 0; n < 8; n++){ calc = 0; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ calc += abs(s[i][j] - ans[n][i][j]); } } min_cost = min(calc, min_cost); } cout << min_cost; return 0; } | cs |