#include <stdlib.h>
#include <stdint.h>
#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include <memory>
#include <algorithm>
#include <deque>
#include <iterator>
#include <numeric>
#include <assert.h>
#include <cstdlib>
#include <sstream>
#include <fstream>
#define INPUT_PATH ""
#define OUTPUT_PATH ""
void algorithm();
int main()
{
algorithm();
return 0;
}
using namespace std;
namespace
{
void flipCol(vector<int>& matrix, int col, int nrRows, int nrCols)
{
for (int row = 0; row < nrRows; ++row)
{
matrix[row*nrCols + col] = -matrix[row*nrCols + col];
}
}
void tryFlippingRows(int& maxSum, int sum, int row, bool sign, int nrCols, int nrRows, vector<int>& matrix)
{
for (int col = 0; col < nrCols; ++col)
{
sum += sign ? matrix[row*nrCols + col] : -matrix[row*nrCols + col];
}
maxSum = max(maxSum, sum);
if (row + 1 < nrRows)
{
tryFlippingRows(maxSum, sum, row + 1, true, nrCols, nrRows, matrix);
tryFlippingRows(maxSum, sum, row + 1, false, nrCols, nrRows, matrix);
}
}
int tryFlippingRows(int nrCols, int nrRows, vector<int>& matrix)
{
int sum = 0;
int maxSum = 0;
tryFlippingRows(maxSum, sum, 0, true, nrCols, nrRows, matrix);
tryFlippingRows(maxSum, sum, 0, false, nrCols, nrRows, matrix);
return maxSum;
}
void tryFlippingCols(int& maxSum, int col, bool sign, int nrCols, int nrRows, vector<int>& matrix)
{
int sum = tryFlippingRows(nrCols, nrRows, matrix);
maxSum = max(sum, maxSum);
if (col + 1 < nrCols)
{
tryFlippingCols(maxSum, col + 1, true, nrCols, nrRows, matrix);
flipCol(matrix, col + 1, nrRows, nrCols);
tryFlippingCols(maxSum, col + 1, false, nrCols, nrRows, matrix);
}
}
int startFlipping(int nrCols, int nrRows, vector<int>& matrix)
{
int maxSum = 0;
tryFlippingCols(maxSum, 0, true, nrCols, nrRows, matrix);
tryFlippingCols(maxSum, 0, false, nrCols, nrRows, matrix);
return maxSum;
}
}
////////////////////////////////////////////////////////////////////////////////
void algorithm()
{
ifstream inputFile(INPUT_PATH "flip.in");
ofstream outputFile(OUTPUT_PATH "flip.out");
//read data from file
int nrRows = 0; inputFile >> nrRows;
int nrCols = 0; inputFile >> nrCols;
vector<int> matrix;
matrix.reserve(nrRows*nrCols);
int readVal = 0;
while (inputFile >> readVal)
{
matrix.push_back(readVal);
}
//end read data from file
int maxSum = startFlipping(nrCols, nrRows, matrix );
outputFile << maxSum;
inputFile.close();
outputFile.close();
}