Cod sursa(job #2192580)

Utilizator georgeromanGeorge Roman georgeroman Data 6 aprilie 2018 16:32:20
Problema Jocul Flip Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.66 kb
#include <fstream>
#include <vector>

typedef std::vector<std::vector<int>> Table;

long flipRow(Table& table, unsigned row) {
  long oldSum = 0, newSum = 0;
  for (unsigned j = 0; j < table[row].capacity(); j++) {
    oldSum += table[row][j];
    table[row][j] *= -1;
    newSum += table[row][j];
  }
  return newSum - oldSum;
}

long flipCol(Table& table, unsigned col) {
  long oldSum = 0, newSum = 0;
  for (unsigned i = 0; i < table.capacity(); i++) {
    oldSum += table[i][col];
    table[i][col] *= -1;
    newSum += table[i][col];
  }
  return newSum - oldSum;
}

long sumOfAll(Table& table) {
  long sum = 0;
  for (unsigned i = 0; i < table.capacity(); i++) {
    for (unsigned j = 0; j < table[i].capacity(); j++) {
      sum += table[i][j];
    }
  }
  return sum;
}

int main() {
  std::ifstream in("flip.in");
  std::ofstream out("flip.out");

  unsigned n, m;
  in >> n >> m;

  Table table = Table();
  table.reserve(n);
  for (unsigned i = 0; i < n; i++) {
    table[i] = std::vector<int>();
    table[i].reserve(m);
  }

  for (unsigned i = 0; i < n; i++) {
    for (unsigned j = 0; j < m; j++) {
      in >> table[i][j];
    }
  }

  bool flippedAny;
  do {
    flippedAny = false;
    for (unsigned j = 0; j < m; j++) {
      for (unsigned i = 0; i < n; i++) {
        if (flipRow(table, i) <= 0) {
          flipRow(table, i);
        } else {
          flippedAny = true;
        }
      }
    }
    for (unsigned i = 0; i < n; i++) {
      for (unsigned j = 0; j < m; j++) {
        if (flipCol(table, j) <= 0) {
          flipCol(table, j);
        } else {
          flippedAny = true;
        }
      }
    }
  } while (flippedAny);

  out << sumOfAll(table);

  return 0;
}