(SPOJ) 1821 - O Bolo de Apostas - Solução
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
Main processando = new Main();
processando.processa();
System.exit(0);
}
static int leitor(BufferedReader br) throws NumberFormatException, IOException {
int n;
int resp = 0;
int sinal = 1;
while (true) {
n = br.read();
if (n >= '0' && n <= '9') break;
if (n == '-') sinal = -1;
if (n == '+') sinal = 1;
}
while (true) {
resp = resp*10 + n-'0';
n = br.read();
if (n < '0' || n > '9') break;
}
return resp*sinal;
}
void processa() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int qteApostas = leitor(br);
while (qteApostas != 0) {
int maximoAtual = 0;
int maximoFinal = -1;
for (int i = 0; i < qteApostas; i++) {
/* Algoritmo de Kadane O(n) */
maximoAtual += leitor(br);
if (maximoAtual < 0) {
maximoAtual = 0;
}
if (maximoAtual > maximoFinal) {
maximoFinal = maximoAtual;
}
}
if (maximoFinal <= 0) {
bw.write("Losing streak.\n");
}
else {
bw.write("The maximum winning streak is " + maximoFinal + ".\n");
}
qteApostas = leitor(br);
}
bw.flush();
bw.close();
return;
}
}
import java.util.*;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
Main processando = new Main();
processando.processa();
System.exit(0);
}
static int leitor(BufferedReader br) throws NumberFormatException, IOException {
int n;
int resp = 0;
int sinal = 1;
while (true) {
n = br.read();
if (n >= '0' && n <= '9') break;
if (n == '-') sinal = -1;
if (n == '+') sinal = 1;
}
while (true) {
resp = resp*10 + n-'0';
n = br.read();
if (n < '0' || n > '9') break;
}
return resp*sinal;
}
void processa() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int qteApostas = leitor(br);
while (qteApostas != 0) {
int maximoAtual = 0;
int maximoFinal = -1;
for (int i = 0; i < qteApostas; i++) {
/* Algoritmo de Kadane O(n) */
maximoAtual += leitor(br);
if (maximoAtual < 0) {
maximoAtual = 0;
}
if (maximoAtual > maximoFinal) {
maximoFinal = maximoAtual;
}
}
if (maximoFinal <= 0) {
bw.write("Losing streak.\n");
}
else {
bw.write("The maximum winning streak is " + maximoFinal + ".\n");
}
qteApostas = leitor(br);
}
bw.flush();
bw.close();
return;
}
}
Comments
Post a Comment