#include <fstream>
const char* inFile = "flip.in";
const char* outFile = "flip.out";
void tryFlipLine(int numLines, int numCols, int* matrix, int lineNum)
{
int sumPositives = 0;
int sumNegatives = 0;
for (int index = 0; index < numCols; ++index)
{
auto elem = matrix[lineNum * numCols + index];
if (elem < 0)
{
sumNegatives -= elem;
}
else
{
sumPositives += elem;
}
}
if (sumNegatives > sumPositives)
{
for (int index = 0; index < numCols; ++index)
{
matrix[lineNum * numCols + index] *= -1;
}
}
}
void tryFlipCol(int numLines, int numCols, int* matrix, int colNum)
{
int sumPositives = 0;
int sumNegatives = 0;
for (int index = 0; index < numLines; ++index)
{
auto elem = matrix[index * numCols + colNum];
if (elem < 0)
{
sumNegatives -= elem;
}
else
{
sumPositives += elem;
}
}
if (sumNegatives > sumPositives)
{
for (int index = 0; index < numLines; ++index)
{
matrix[index * numCols + colNum] *= -1;
}
}
}
int flip(int numLines, int numCols, int* matrix)
{
for (auto l = 0; l < numLines; ++l)
{
tryFlipLine(numLines, numCols, matrix, l);
}
for (auto c = 0; c < numCols; ++c)
{
tryFlipCol(numLines, numCols, matrix, c);
}
int sum = 0;
for (auto i = 0; i < numLines * numCols; ++i)
{
sum += matrix[i];
}
return sum;
}
int main()
{
int numLines = 0;
int numCols = 0;
std::ifstream readFile(inFile);
if (!readFile) return -1;
readFile >> numLines >> numCols;
int* matrix = new int[numLines*numCols];
for (int index = 0; index < numLines * numCols; ++index)
{
readFile >> matrix[index];
}
auto sum = flip(numLines, numCols, matrix);
return 0;
}