Cod sursa(job #759409)

Utilizator andrei213Andrei Cibotaru andrei213 Data 17 iunie 2012 22:39:04
Problema Jocul Flip Scor 30
Compilator c Status done
Runda Arhiva de probleme Marime 2.15 kb
#include <stdio.h>
#include <malloc.h>
//check the data types such as ‘long int **’ but argument is of type ‘long int (*)[16]’


char check_positive_row(long int *mat, int limit);
void flip_row(long int **mat, int limit);

char check_positive_col(long int **mat, int limit, int col);
void flip_col(long int ***mat, int limit, int col);


int main (){
FILE *in = NULL, *out = NULL;
int n,m,i,j;
long int **mat = NULL;
char changed = 1;
long int sum = 0 ;

if ((in = fopen ("flip.in", "r")) == NULL)
	{printf ("Input could not be opened\n"); return -1; }
if ((out = fopen ("flip.out","w")) == NULL)
	{printf ("Output could not be opened \n"); return -1;}

fscanf(in, "%d %d\n",&n, &m);



mat = (long int **)malloc(n * sizeof(long int *));
for (i = 0 ; i < n ; i++){
	mat[i] = (long int *) malloc(m * sizeof(long int));
}

for (i = 0 ; i < n ; ++i)
   for (j = 0 ; j < m ; ++j){
	fscanf (in , "%ld", &mat[i][j]);
}


while (changed){
changed = 0;
//go through lines first
for (i = 0 ; i < n; i++){
   //check whether the sum on the line is positive, if not flip
   if (!check_positive_row(mat[i],m))
	{flip_row(&(mat[i]), m); changed = 1;}
//	printf ("row %d", i);
}

//go through lines first
for (i = 0 ; i < m; i++){
   //check whether the sum on the line is positive, if not flip
   if (!check_positive_col(mat,n,i))
	{flip_col(&mat, n,i); changed = 1;}
//	printf ("row %d", i);
}
}// end of while
for (i = 0 ; i < n ; ++i){
   for (j = 0 ; j < m ; ++j)
	sum += mat[i][j];
}

fprintf(out , "%ld\n",sum );

for (i = 0 ; i < n ; i++){
    free(mat[i]);
}

free(mat);

fclose(in);
fclose(out); 
return 0;
}


char check_positive_col(long int **mat, int limit, int col){
long int sum = 0, i= 0;

for (i =0 ; i < limit ; ++i){
	sum += mat[i][col];
}

if (sum < 0) return 0;

return 1;
}


void flip_col(long int ***mat, int limit, int col){
long int i = 0 ;

for (i =0 ; i < limit ; ++i){
	(*mat)[i][col] *= -1;
}

}

char check_positive_row(long int *mat , int limit){
long int sum = 0;
int i=0;
for (i = 0; i < limit; i++){
	sum += *(mat+i);
}
if (sum < 0 ) return 0;
else
return 1;
}

void flip_row(long int **mat, int limit){
	int i = 0;
	
for (i = 0 ; i < limit ; ++i  )
		(*mat)[i] *= -1;

}