Cod sursa(job #551360)

Utilizator svoprea1Silviu Vlad Oprea svoprea1 Data 10 martie 2011 17:42:19
Problema Jocul Flip Scor 100
Compilator c Status done
Runda Arhiva de probleme Marime 1.68 kb
#include <stdio.h>
#include <stdlib.h>

void
max_sum(int**, int);

void
current_sum(int**);

int result, n, m, *a;

int
main(int argc, char **argv)
{
	int   i, j, **v;
	FILE  *f;

	if ((f = fopen("flip.in", "r")) == NULL)
	{
		perror("Cannot open destination file...\n");
		return -1;
	}

	if (fscanf(f, "%d %d\n", &n, &m) != 2)
	{
		printf("Cannot read from file ...\n");
		return -1;
	}

	if ((v = (int**)malloc(sizeof(int*) * n)) == NULL)
	{
		perror("Can't allocate memory");
		return -1;
	}

	for (i = 0; i < n; i++)
		if ((*(v + i) = (int*)malloc(sizeof(int) * m)) == NULL)
			{
				perror("Can't allocate memory");
				return -1;
			}
		

	/* Reading matrix */
	for (i = 0; i < n; i++)
	{
		for (j= 0; j < m; j++)
		{
			if (fscanf(f, "%d", (*(v + i) + j)) != 1)
				{
					printf("Cannot read from file...\n");
					return -1;
				}
		}
	}

	if (fclose(f) == EOF)
		perror("Cannot close source file...\n");

	if ((f = fopen("flip.out", "w")) == NULL)
	{
		perror("Cannot open destination file...\n");
		return -1;
	}

	result = 0;
	a = (int*)malloc(sizeof(int) * n);
	max_sum(v, 0);
	printf("%d\n", result);
	if (fprintf(f, "%d", result) < 0)
	{
		printf("Cannot write to file...\n");
		return -1;
		}

	if (fclose(f) == EOF)
	{
		perror("Cannot close destination file...\n");
		return -1;
	}

	free(a);

	for (i = 0; i < n; i++)
		free(*(v+i));

	free(v);

	return 0;
}

void
max_sum(int **v, int ind)
{
	if (ind < n)
	{
		a[ind] = 1;
		max_sum(v, ind+1);
		current_sum(v);
		a[ind] = -1;
		max_sum(v, ind+1);
	}
}

void
current_sum(int **v)
{
	int s, t = 0, i, j;
	
	for (i = 0; i < m; i++)
	{
		s = 0;
		for (j = 0; j < n; j++)
			s += v[j][i] * a[j];
		t += s > 0? s : -1*s;
	}
	if (t > result) result = t;
}