using System;
using System.IO;
namespace ShortestPath
{
class Program
{
static int[,] ReadFromFile(string fileName)
{
using (Stream inp = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (TextReader reader = new StreamReader(inp))
{
string tmpString;
string[] tmpTokens;
tmpString = reader.ReadLine();
tmpTokens = tmpString.Split(' ');
int colCount = int.Parse(tmpTokens[0]);
int rowSize = int.Parse(tmpTokens[1]);
int[,] res = new int[colCount, rowSize];
for (int y = 0; y < colCount; y++)
{
tmpString = reader.ReadLine();
tmpTokens = tmpString.Split(' ');
for (int x = 0; x < rowSize; x++)
{
res[y, x] = int.Parse(tmpTokens[x]);
}
}
return res;
}
}
static void Main(string[] args)
{
int[,] penalty = ReadFromFile("input.txt");
//int[,] penalty = new int[,]
// {
// {3, 2, 8, 6, 4,},
// {4, 7, 12, 9, 1},
// {55, 8, 3, 2, 8},
// {20, 7, 4, 9, 1},
// };
//int[,] penalty = new int[,] {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 2, 2, 2}, {1, 1, 1, 1}};
int rowSize = penalty.GetLength(1);
int colCount = penalty.GetLength(0);
int[,] indFrom = new int[colCount, rowSize];
int[,] sum = new int[colCount, rowSize];
for (int x = 0; x < rowSize; x++)
{
indFrom[0, x] = -1;
sum[0, x] = penalty[0, x];
//Console.Write(sum[0, x] + "\t");
}
//Console.WriteLine();
for (int y = 1; y < colCount; y++)
{
for (int x = 0; x < rowSize; x++)
{
int[] p = new int[]{
(x == 0) ? int.MaxValue : sum[y - 1, x - 1],
sum[y - 1, x],
(x == rowSize - 1) ? int.MaxValue : sum[y - 1, x+1],
};
int minInd = 0;
for (int i = 1; i < p.Length; i++)
{
if (p[i] < p[minInd]) minInd = i;
}
indFrom[y, x] = minInd + (x - 1);
sum[y, x] = p[minInd] + penalty[y, x];
//Console.Write(sum[y, x] + "\t");
}
//Console.WriteLine();
}
{
int minInd = 0;
for (int i = 1; i < rowSize; i++)
{
if (sum[colCount - 1, i] < sum[colCount - 1, minInd]) minInd = i;
}
Console.WriteLine(sum[colCount - 1, minInd]);
int[] optPen = new int[colCount];
for (int y = colCount - 1; y >= 0; y--)
{
optPen[y] = penalty[y, minInd];
minInd = indFrom[y, minInd];
}
for (int y = 0; y < colCount; y++)
{
Console.Write(optPen[y] + " ");
}
Console.WriteLine();
}
}
}
}