Minuses
Time limit1sMemory limit128 MB
Given a signed sum of distinct variables, find the fewest bracket pairs needed to turn the all-minus chain into an equivalent expression.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, Math, Implementation
- Solved
- No attempts yet
Problem
Subtraction is not associative. For example but , so . This means the value of an expression such as depends on the order in which the subtractions are performed. When there are no brackets we agree to evaluate from left to right, so means .
You are given an expression of the form where each is either or , and are pairwise distinct variables.
We want to insert brackets into the all-minus expression so that it becomes equivalent to the given expression (the two expressions are equal for every value of the variables). At most pairs of brackets may be inserted, and no pair of brackets may enclose zero or one variable.
For example, to match we may bracket as This is only one of many possible bracketings, and it is not necessarily one that uses the fewest pairs. Determine the minimum number of bracket pairs over all valid bracketings.
Input
The first line contains an integer (), the number of variables in the given expression. Each of the next lines contains a single character, or . The -th of these lines () is the sign between and in the given expression. You may assume that a valid bracketing always exists for the input.
Output
Print a single integer: the minimum number of bracket pairs that must be inserted into to obtain an expression equivalent to the given one.