Cod sursa(job #2830964)

Utilizator ciprian.morosanuCiprian Morosanu ciprian.morosanu Data 10 ianuarie 2022 16:18:03
Problema Jocul Flip Scor 100
Compilator c-64 Status done
Runda Arhiva de probleme Marime 2.03 kb
#include <stdio.h>

#define MAX_ROWS 16
#define MAX_COLS 16

typedef struct {
    int maxSum;
    int rowToggle[MAX_ROWS];
    int currentRow;
    int matrix[MAX_ROWS][MAX_COLS];
    int cloneMatrix[MAX_ROWS][MAX_COLS];
    int rows;
    int cols;
} Context;

void solve(Context *context) {
    int currentRow = context->currentRow;
    if (currentRow == context->rows) {
        return;
    }
    for (int i = 0; i < 2; ++i) {
        context->rowToggle[currentRow] = (i % 2 == 0) ? 1 : -1;
        context->currentRow++;
        solve(context);
        context->currentRow = currentRow;
        if (currentRow == context->rows - 1) {
            int colSum[MAX_COLS] = {0};
            for (int col = 0; col < context->cols; ++col) {
                for (int row = 0; row < context->rows; ++row) {
                    context->cloneMatrix[row][col] = context->matrix[row][col] * context->rowToggle[row];
                    colSum[col] += context->cloneMatrix[row][col];
                }
            }
            int sum = 0;
            for (int col = 0; col < context->cols; ++col) {
                sum += (colSum[col] < 0) ? -colSum[col] : colSum[col];
            }
            if (sum > context->maxSum) {
                context->maxSum = sum;
            }
        }
    }
}

int main() {
    char *inFileName = "flip.in";
    char *outFileName = "flip.out";
    FILE *in = fopen(inFileName, "r");
    if (in == NULL) {
        printf("Cannot open %s.\n", inFileName);
        return 1;
    }
    FILE *out = fopen(outFileName, "w");
    int rows;
    int cols;
    fscanf(in, "%d %d", &rows, &cols);
    Context context;
    context.rows = rows;
    context.cols = cols;
    context.currentRow = 0;
    int maxSum = 0;
    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < cols; ++col) {
            fscanf(in, "%d", &context.matrix[row][col]);
            maxSum += context.matrix[row][col];
        }
    }
    context.maxSum = maxSum;
    solve(&context);
    fprintf(out, "%d", context.maxSum);
    fclose(in);
    fclose(out);
    return 0;
}