Pages

Friday, December 14, 2007

USACO: Broken Necklace

/*
ID: wsoethe1
LANG: JAVA
TASK: beads
*/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class beads {
public static void main(String[] args) {
try {
BufferedReader fileIn = new BufferedReader(new FileReader(
"beads.in"));
PrintWriter fileOut = new PrintWriter(new BufferedWriter(
new FileWriter("beads.out")));
try {
int qtde = Integer.parseInt(fileIn.readLine());
String colar = fileIn.readLine();
char letra = 'w';
char letraTemp = 'w';
int comeco = 0;
for (int i = 0; i < qtde; i++) {
letra = colar.charAt(i);
if (letra != 'w')
break;
}
boolean entrou = false;
for (int i = qtde - 1; i >= 0; i--) {
letraTemp = colar.charAt(i);
if (letra != 'w' && letraTemp != 'w') {
if (letraTemp != letra) {
comeco = i + 1;
entrou = true;
break;
}
}

}
if (entrou) {
colar += colar;
int tamanho = 0;
boolean check = true;
boolean check2 = true;
int posicao = 0;
int tamanhoFinal = 0;
qtde = qtde * 2;

for (int i = comeco; i < qtde; i++) {
letraTemp = colar.charAt(i);
if (letraTemp == 'w' || letra == letraTemp) {
tamanho++;
} else {
if (check) {
posicao = i;
if (letra == 'b')
letra = 'r';
else
letra = 'b';
check = false;
tamanho++;
} else {
if (tamanhoFinal < tamanho)
tamanhoFinal = tamanho;
else {
if (check2) {
qtde = posicao;
i = posicao - comeco;
check2 = false;
}
}
tamanho = 0;
check = true;
}
}
}
if (tamanhoFinal < tamanho)
tamanhoFinal = tamanho;
fileOut.write(tamanhoFinal + "\n");
} else {
fileOut.write(qtde + "\n");
}

} finally {
fileIn.close();
fileOut.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

No comments :