Pagini recente » Cod sursa (job #1774659) | Cod sursa (job #3176846) | Cod sursa (job #1289636) | Cod sursa (job #2884776) | Cod sursa (job #793843)
Cod sursa(job #793843)
#include <stdio.h>
#include <malloc.h>
//check the data types such as ‘long int **’ but argument is of type ‘long int (*)[16]’
#define MAX_SIZE 16
struct matrix {
long int mat[16][16];
int n,m;
};
char check_positive_row(struct matrix *mat, int row);
void flip_row(struct matrix *mat, int row);
char check_positive_col(struct matrix *mat, int col);
void flip_col(struct matrix *mat, int col);
struct matrix compute_row(struct matrix *mat);
struct matrix compute_col(struct matrix *mat);
long int sum(struct matrix *mat);
int main ()
{
FILE *in = NULL, *out = NULL;
int n,m,i,j;
long int **mat = NULL;
char changed = 1;
long int sum2 = 0, sum1=0;
long int prevsum = 0;
struct matrix inputMat, rowmat, colmat;
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",&inputMat.n, &inputMat.m);
for (i = 0 ; i < inputMat.n ; ++i)
for (j = 0 ; j < inputMat.m ; ++j){
fscanf (in , "%ld", &inputMat.mat[i][j]);
}
prevsum = sum (&inputMat);
while (changed){
changed = 0;
colmat = compute_col(&inputMat);
rowmat = compute_row(&inputMat);
sum1 = sum(&colmat);
sum2 = sum(&rowmat);
if (sum1 > sum2){
if (sum1 > prevsum ){
changed = 1;
inputMat = colmat;
}
}
else
{
if (sum2 > prevsum ){
changed = 1;
inputMat = rowmat;
}
}
prevsum = sum(&inputMat);
}
// calculate line and column
//check which has a greater sum
// check whether the greater sum is the same as the previous step, if it is then we have finished
fprintf(out , "%ld\n",prevsum );
fclose(in);
fclose(out);
return 0;
}
long int sum (struct matrix *mat){
int i,j;
long int result=0;
for (i = 0; i < mat->n; i++ )
for (j =0 ; j < mat->m ; ++j){
result += mat->mat[i][j];
}
return result;
}
struct matrix compute_col(struct matrix *mat){
int i ;
struct matrix result = *mat;
for (i = 0 ; i < result.m; i++){
if (!check_positive_col(&result, i))
flip_col(&result, i);
}
return result;
}
struct matrix compute_row(struct matrix *mat){
int i ;
struct matrix result = *mat;
for (i = 0 ; i < result.n; i++){
if (!check_positive_row(&result, i))
flip_row(&result, i);
}
return result;
}
char check_positive_col(struct matrix *s_mat, int col){
long int sum = 0, i= 0;
for (i =0 ; i < s_mat->n ; ++i){
sum += s_mat->mat[i][col];
}
if (sum < 0) return 0;
return 1;
}
void flip_col(struct matrix *s_mat, int col){
long int i = 0 ;
//init result
for (i =0 ; i < s_mat->n ; ++i){
s_mat->mat[i][col] *= (-1);
}
}
char check_positive_row(struct matrix *s_mat , int row){
long int sum = 0;
int i=0;
for (i = 0; i < s_mat->m ; i++){
sum += (*s_mat).mat[row][i];
}
if (sum < 0 ) return 0;
return 1;
}
void flip_row(struct matrix *s_mat, int row){
int i = 0;
for (i = 0 ; i < s_mat->m ; ++i )
s_mat->mat[row][i] *= (-1);
}