Cod sursa(job #1014062)

Utilizator razvan9310FMI - Razvan Damachi razvan9310 Data 22 octombrie 2013 00:10:52
Problema Elimin Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.13 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <bitset>
using namespace std;

int M, N, R, C, MAX, total;
vector<vector<int> > mat;
vector<int> sum_row, sum_col;
bitset<7295> sol;
ifstream in("elimin.in");
ofstream out("elimin.out");

void input() {
  in>>M>>N>>R>>C;
  sum_row.resize(M);
  sum_col.resize(N);
  for (int i = 0; i < M; ++i) {
    vector<int> row(N, 0);
    mat.push_back(row);
    int val, sum = 0;
    for (int j = 0; j < N; ++j) {
      in>>val;
      mat[i][j] = val;
      sum += val;
      sum_col[j] += val;
    }
    total += sum;
    sum_row[i] = sum;
  }
}

void columnSort(int total) {
  int i, j;
  for (i = 0; i < N; ++i) {
    sum_col[i] = 0;
  }
  for (i = 0; i < M; ++i) {
    if (!sol[i]) {
      for (j = 0; j < N; ++j) {
        sum_col[j] += mat[i][j];
      }
    }
  }

  sort(sum_col.begin(), sum_col.end());
  for (i = 0; i < C && total > MAX; ++i) {
    total -= sum_col[i];
  }
  if (total > MAX) {
    MAX = total;
  }
}

void rowSort(int total) {
  int i, j;
  for (i = 0; i < M; ++i) {
    int sum = 0;
    for (j = 0; j < N; ++j) {
      if (!sol[j]) {
        sum += mat[i][j];
      }
    }
    sum_row[i] = sum;
  }
  sort(sum_row.begin(), sum_row.end());
  for (i = 0; i < R && total > MAX; ++i) {
    total -= sum_row[i];
  }
  if (total > MAX) {
    MAX = total;
  }
}

void backPeLinii(const int &pos, const int &lvl, const int &total) {
  if (lvl == R) {
    columnSort(total);
    return;
  }
  for (int i = pos + 1; (i < M) && (M - i - R + lvl >= 0); ++i) {
    int newtotal = total - sum_row[i];
    if (newtotal > MAX) {
      sol[i] = 1;
      backPeLinii(i, lvl + 1, newtotal);
      sol[i] = 0;
    }
  }
}

void backPeColoane(const int &pos, const int &lvl, const int &total) {
  if (lvl == C) {
    rowSort(total);
    return;
  }
  for (int i = pos + 1; (i < N) && (N - i - C + lvl >= 0); ++i) {
    int newtotal = total - sum_col[i];
    if (newtotal > MAX) {
      sol[i] = 1;
      backPeColoane(i, lvl + 1, newtotal);
      sol[i] = 0;
    }
  }
}

int main() {
  input();
  if (M < N) {
    backPeLinii(-1, 0, total);
  } else {
    backPeColoane(-1, 0, total);
  }
  out<<MAX;
  return 0;
}