Cod sursa(job #2630780)

Utilizator OctavianCGOctavian Chiliment OctavianCG Data 27 iunie 2020 09:33:41
Problema Jocul Flip Scor 0
Compilator cpp-32 Status done
Runda Arhiva de probleme Marime 1.99 kb
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

long **t, r;
int n, m;

bool b_t(long** t, long* t_s) {
	long s_t, s_f, s_max = LONG_MIN;
	long** s = (long**)malloc(sizeof(long*) * n);
	if (s == NULL) {
		printf("Eroare la alocare dinamica!\n");
		return false;
	}
	for (int i = 0; i < n; i++) {
		s[i] = (long*)malloc(sizeof(long) * m);
		if (s[i] == NULL) {
			printf("Eroare la alocare dinamica!\n");
			for (int j = 0; j < i; j++)
				free(s[i]);
			free(s);
			return 0;
		}
	}
	for (int i = 0; i < 1 << n; i++) {
		s_f = 0;
		for (int j = 0; j < n; j++)
			for (int k = 0; k < m; k++)
				s[j][k] = t[j][k];
		for (int j = 0; j < n; j++)
			if (i >> j & 1) {
				for (int k = 0; k < m; k++)
					s[j][k] *= -1;
			}
		for (int j = 0; j < m; j++) {
			s_t = 0;
			for (int k = 0; k < n; k++)
				s_t += s[k][j];
			if (s_t < 0) {
				for (int k = 0; k < n; k++)
					s[k][j] *= -1;
				s_t *= -1;
			}
			s_f += s_t;
		}
		if (s_f > s_max)
			s_max = s_f;
	}
	*t_s = s_max;
	for (int i = 0; i < n; i++)
		free(s[i]);
	free(s);
	return true;
}


int main() {
	FILE* fis;
	fopen_s(&fis, "flip.in", "r");
	if (fis == NULL) {
		printf("Nu s-a putut deschide fisierul!\n");
		return -1;
	}
	fscanf_s(fis, "%d %d", &n, &m);
	t = (long**)malloc(sizeof(long*) * n);
	if (t == NULL) {
		printf("Nu s-a putut aloca matricea!\n");
		return -1;
	}
	for (int i = 0; i < n; i++) {
		t[i] = (long*)malloc(sizeof(long) * m);
		if (t[i] == NULL) {
			printf("Eroare la alocarea dinamica a matricei!\n");
			for (int j = 0; j < i; j++)
				free(t[i]);
			free(t);
			return -1;
		}
	}
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			fscanf_s(fis, "%ld", &t[i][j]);
	fclose(fis);
	if (b_t(t, &r)) {
		fopen_s(&fis, "flip.out", "w");
		if (fis != NULL) {
			fprintf_s(fis, "%ld", r);
			fclose(fis);
		}
		else
			printf("Nu s-a putut genera fisierul de iesire!");
	}
	for (int i = 0; i < n; i++)
		free(t[i]);
	free(t);
	return 0;
}