Skip to content

Instantly share code, notes, and snippets.

@stphung
Created April 26, 2011 16:31
Show Gist options
  • Select an option

  • Save stphung/942610 to your computer and use it in GitHub Desktop.

Select an option

Save stphung/942610 to your computer and use it in GitHub Desktop.
TopCoder SRM 504 Division 2 - 500 point problem
import java.util.Stack;
public class MathContest {
public int countBlack(String ballSequence, int repetitions) {
String newBallSequence = ballSequence;
Stack<Integer> stack = new Stack<Integer>();
for (int i = newBallSequence.length() - 1; i >= 0; i--) {
if (newBallSequence.charAt(i) == 'B')
stack.push(1);
else
stack.push(-1);
}
int black = 0;
boolean white = false;
while (stack.size() > 0) {
int pop = stack.pop();
if (pop == 1) {
black++;
stack = invert(stack);
} else {
white = true;
stack = reorder(stack);
}
}
if (white)
return black;
return black * repetitions;
}
public Stack<Integer> reorder(Stack<Integer> stack) {
Stack<Integer> temp = new Stack<Integer>();
while (stack.size() > 0)
temp.push(stack.pop());
return temp;
}
public Stack<Integer> invert(Stack<Integer> stack) {
Stack<Integer> temp = new Stack<Integer>();
while (stack.size() > 0)
temp.push(stack.pop());
while (temp.size() > 0) {
stack.push(-temp.pop());
}
return stack;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment