Cod sursa(job #2594361)

Utilizator benisavuSavu Beniamin benisavu Data 5 aprilie 2020 19:43:47
Problema Jocul Flip Scor 30
Compilator java Status done
Runda Arhiva de probleme Marime 2.88 kb
//package com.beniamin.savu.flip;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Hello world!
 *
 */
public class Main {
	
	
	public static void main(String[] args) {
		FileReader fileReader = new FileReader();
		fileReader.open("flip.in");
		
		int n = fileReader.nexInt();
		int m = fileReader.nexInt();
		int[][] values = new int[n][m];
		
		int total = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				values[i][j] = fileReader.nexInt();
				total += values[i][j];
			}
		}
		
		String type = "undefined";
		int  position = -1;
		int maxValue = 0;
		while (true) {
			maxValue = 0;
			for (int i = 0; i < n; i++) {
				int lineTotal = 0;
				for (int j = 0; j < m; j++) {
					lineTotal += values[i][j] * (-1);
				}
				if(lineTotal != 0 && lineTotal > maxValue) {
					maxValue = lineTotal;
					position = i;
					type = "line";
				}
			}
			
			for (int j = 0; j < m; j++) {
				int columnTotal = 0;
				for (int i = 0; i < n; i++) {
					columnTotal += values[i][j] * (-1);
				}
				if(columnTotal != 0 && columnTotal > maxValue) {
					maxValue = columnTotal;
					position = j;
					type = "column";
				}
			}
			
			if(type.equals("line")) {
				for(int j = 0; j < m; j++) {
					values[position][j] *= -1;
				}
			} else {
				for (int i = 0; i < n; i++) {
					values[i][position] *= -1;
				}
			}
			
			int newTotal = 0;
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < m; j++) {
					newTotal += values[i][j];
				}
			}
			
			if(newTotal > total) {
				total = newTotal;
			} else {
				break;
			}
		} 
		
		StringBuffer result = new StringBuffer();
		result.append(total);
		FileWriter.write(result.toString(), "flip.out");
	}
}

/**
 * Reads the content of a file.
 * 
 * @author benis
 *
 */
class FileReader {

	/**
	 * The reader.
	 */
	private Scanner reader;
	
	/**
	 * Reads the contents of the file.
	 */
	public void open(String filePath) {
		try {
			reader = new Scanner(new FileInputStream(filePath));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
	}
	
	/**
	 * Reads the next integer.
	 * 
	 * @return The integer.
	 */
	public int nexInt() {
		return reader.nextInt();
	}
	
	/**
	 * Closes the connection with the file.
	 */
	public void close() {
		reader.close();
	}

}

/**
 * Writes content to a file.
 * 
 * @author benis
 *
 */
class FileWriter {

	/**
	 * Writes the given content to the given file.
	 *
	 * @param content The content to write.
	 * @param filePath The file path
	 */
	public static void write(String content, String filePath) {
		try (PrintWriter writer = new PrintWriter(filePath)) {
			writer.write(content + "\n");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}