Cod sursa(job #551322)

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

void
max_sum(int**, int, int);

void
compute(int**, int, int, int);

void
current_sum(int**, int, int, int);

int result;

int
main(int argc, char **argv)
{
	int   n, m, 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;
	max_sum(v, n, m);
	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;
	}

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

	free(v);

	return 0;
}

void
max_sum(int **v, int n, int m)
{
	int ind = 0;
	while (ind < n)
		current_sum(v, n , m, ind++);
}

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