Cod sursa(job #950189)

Utilizator dpopovicDana Popovici dpopovic Data 16 mai 2013 01:28:02
Problema Jocul Flip Scor 50
Compilator c Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <stdio.h>
#include <stdlib.h>

long ** create_array(int nbi, int nbj) {
	int i, j; i = j = 0;
	long ** res = (long **) malloc(sizeof(long*) * nbi);
	while(i < nbi) {
		res[i++] = (long *) malloc(sizeof(long) * nbj);
	}
	return res;
}

long ** readFlip(int * nbi, int * nbj) {
	FILE *fp;
	int i, j; i = j = 0;
	fp = fopen("flip.in", "r");
	fscanf(fp, "%d %d\n", nbi, nbj);
	long ** res = create_array(*nbi, *nbj);
	while(i < *nbi) {
		while(j < *nbj) {
			fscanf(fp, "%ld ", &(res[i][j++]));
		}
		i++;
		j=0;
	}
	fclose(fp);
	return res;
}

void writeFlip(long value) {
	FILE *fp;
	fp = fopen("flip.out", "w");
	fprintf(fp, "%ld\n", value);
	fclose(fp);
}

void flipi(long ** t, int i, int nbj) {
	int j = 0;
	while(j < nbj) {
		t[i][j++] *= -1;
	}
}

long sumi(long ** t, int i, int nbj) {
	long r = 0;
	int j = 0;
	while(j < nbj) {
		r += t[i][j++];
	}
	return r;
}

void flipj(long ** t, int nbi, int j) {
	int i = 0;
	while(i < nbi) {
		t[i++][j] *= -1;
	}
}

long sumj(long ** t, int nbi, int j) {
	long r = 0;
	int i = 0;
	while(i < nbi) {
		r += t[i++][j];
	}
	return r;
}

long get_sum(long ** t, int nbi, int nbj) {
	printf("========================================\n");
	int i, j;
	i = j = 0;
	long total = 0;
	while(i < nbi) {
		total += sumi(t, i, nbj);
		while(j < nbj) {
			printf("%ld ", t[i][j++]);
		}
		j = 0;
		printf("\n");
		i++;
	}
	printf("TOTAL : %ld\n", total);
	printf("========================================\n");
	return total;
}

int main (int argc, const char * argv[]) {
	int i, j, nbflip, nbi, nbj;
	i = j = 0;
	nbflip = 1;
	long ** tab = readFlip(&nbi, &nbj);
	printf("%d %d\n", nbi, nbj);
	get_sum(tab, nbi, nbj);
	while(nbflip > 0) {
		nbflip = 0;
		while(i < nbi) {
			while(j < nbj) {
				if(tab[i][j] > 0 && sumi(tab, i, nbj) + sumj(tab, nbi, j) - 2 * tab[i][j] < 0) {
					flipi(tab, i, nbj);
					flipj(tab, nbi, j);
				}
				j++;
			}
			j = 0;
			i++;
		}
		i = 0;
		while(i < nbi) {
			if(sumi(tab, i, nbj) < 0) {
				flipi(tab, i, nbj);
				nbflip ++;
			}
			i++;
		}
		i = 0;
		while(j < nbj) {
			if(sumj(tab, nbi, j) < 0) {
				flipj(tab, nbi, j);
				nbflip ++;
			}
			j++;
		}
		j = 0;
		get_sum(tab, nbi, nbj);
	}
	writeFlip(get_sum(tab, nbi, nbj));
    return 0;
}