using System; using System.Collections.Generic; using System.IO; class Solution { static int[] s = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; static public void nextPerm() { int i = -1; int j = 0; for (int x = s.Length - 2; x >= 0; x--) if (s[x] < s[x + 1]) { i = x; break; } if (-1 == i) return; for (int x = s.Length - 1; x > i; x--) if (s[x] > s[i]) { j = x; break; } // Swap i and j int temp = s[i]; s[i] = s[j]; s[j] = temp; Array.Reverse(s, i + 1, s.Length - (i + 1)); // Reverse after } static bool isMagic() { return s[0] + s[1] + s[2] == 15 && s[3] + s[4] + s[5] == 15 && s[6] + s[7] + s[8] == 15 && s[0] + s[3] + s[6] == 15 && s[1] + s[4] + s[7] == 15 && s[2] + s[5] + s[8] == 15 && s[0] + s[4] + s[8] == 15 && s[2] + s[4] + s[6] == 15; } static void print() { foreach (var t in s) { Console.Write(t); Console.Write(' '); } Console.WriteLine(); } static void Main(String[] args) { var a = new int[9]; for (int i = 0; i < 3; ++i) { var t = Console.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); for (int j = 0; j < 3; ++j) a[i * 3 + j] = int.Parse(t[j]); } var ans = int.MaxValue; //print(); for (int q = 0; q < 362880; ++q) { if (isMagic()) { //print(); ; var weight = 0; for (int i = 0; i < 9; ++i) weight += Math.Abs(a[i] - s[i]); ans = Math.Min(ans, weight); } nextPerm(); } //print(); Console.WriteLine(ans); } }