Cod sursa(job #551226)

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

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

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;
				}
			// printf("%d ", v[i][j]);
		}
		// printf("\n");
	}

	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;
	}

	if (fprintf(f, "%d", max_sum(v, n, m)) < 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;
}

int
max_sum(int **v, int n, int m)
{
	int i, j, neg = 0, poz = 0, r = 0;

	for (i = 0; i < n; i++)
	{
		neg = poz = 0;
		for (j = 0;j < m; j++)
		{
			if (v[i][j] < 0)
				neg += v[i][j];
	    else
				poz += v[i][j];
			if (-1*neg > poz)
			{
				neg *= -1;
				poz *= -1;
			}
		}
		r += poz + neg;
	}

	for (i = 0; i < m; i++)
	{

		neg = poz = 0;
		for (j = 0;j < n; j++)
		{
			if (v[j][i] < 0)
				neg += v[j][i];
	    else
				poz += v[j][i];
		}
		if (-1*neg > poz)
		{
			neg *= -1;
			poz *=-1;
			r += 2*(poz + neg);
		}
	}
	return r;
}