Cod sursa(job #2027462)

Utilizator adipopaAdrian Popa adipopa Data 26 septembrie 2017 09:41:29
Problema Jocul Flip Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.87 kb
#include <fstream>
#include <cmath>

using namespace std;

ifstream fin("flip.in");
ofstream fout("flip.out");

int n, m;
int x[16][16];

void readData() {
    fin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            fin >> x[i][j];
        }
    }
}

void revertLine(int i) {
    for (int j = 0; j < n; j++) {
        x[i][j] = -x[i][j];
    }
}

void revertColumn(int i) {
    for (int j = 0; j < n; j++) {
        x[j][i] = -x[j][i];
    }
}

void flip() {
    // Check every line of the array and switch it by -1 if the amount of negative numbers is greater
    // than the amount of positive numbers
    for (int i = 0; i < n; i++) {
        int posSum = 0;
        int negSum = 0;
        for (int j = 0; j < m; j++) {
            if (x[i][j] >= 0) {
                posSum += x[i][j];
            } else {
                negSum += x[i][j];
            }
        }
        if (posSum < abs(negSum)) {
            revertLine(i);
        }
    }

    // Check every column of the array and switch it by -1 if the amount of negative numbers is greater
    // than the amount of positive numbers
    for (int i = 0; i < m; i++) {
        int posSum = 0;
        int negSum = 0;
        for (int j = 0; j < n; j++) {
            if (x[j][i] >= 0) {
                posSum += x[j][i];
            } else {
                negSum += x[j][i];
            }
        }
        if (posSum < abs(negSum)) {
            revertColumn(i);
        }
    }
}

void solve() {
    flip();

    int sum = 0;

    // Add the elements and print out the sum. This sum is the maximum value after running "flip"
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            sum += x[i][j];
        }
    }

    fout << sum;
}

int main() {
    readData();
    solve();
    return 0;
}