Created
April 26, 2011 16:31
-
-
Save stphung/942610 to your computer and use it in GitHub Desktop.
TopCoder SRM 504 Division 2 - 500 point problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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