This page is still under construction.

Parts of this page are still being built. What you see may change.

Printed-Circuit Boards

Time limit3sMemory limit128 MB

Summary
Given a series-parallel circuit described recursively, find the minimum number of connections that must be routed on the top side so every unit is reached from the top.
Level

Medium7 of 10

Topics
Tree, Dynamic programming, Greedy, Recursion
Solved
No attempts yet

Problem

The company Bytel has started producing series-parallel electronic circuits. Every such circuit is made of electronic units, of connections between the units, and of two power connections. A series-parallel circuit is one of the following:

  • a single unit;

  • several smaller series-parallel circuits joined in series;

  • two branching units that join several smaller series-parallel circuits in parallel.

The circuits are mounted on two-sided printed-circuit boards, so every connection runs either on the top side or on the bottom side of the board. To keep manufacturing cheap, as many connections as possible should run on the bottom side; however, every unit must have at least one connection reaching it from the top side.

Write a program that:

  • reads the description of a series-parallel circuit,
  • computes the minimum number of connections that must run on the top side of the board,
  • prints that number.

Input

The input contains the description of one series-parallel circuit, given in a recursive form:

  • a line S n, where 2≤n≤100002 \le n \le 10000, means the circuit consists of nn smaller circuits joined in series; their descriptions follow on the next lines;
  • a line R n, where 2≤n≤100002 \le n \le 10000, means the circuit consists of nn smaller circuits joined in parallel (through two branching units); their descriptions follow on the next lines;
  • a line containing a single letter X describes a circuit made of exactly one unit.

The total number of X letters in the description does not exceed 10710^7, and the nesting depth of the description does not exceed 500500.

Output

Print a single integer: the minimum number of connections that must run on the top side of the board.

Examples3

  1. Example 1

    Input
    R 3
    S 2
    X
    R 2
    S 2
    X
    X
    S 2
    X
    X
    S 3
    X
    X
    X
    R 2
    X
    X
    
    Expected output
    8
    
  2. Example 2

    Input
    S 2
    X
    X
    
    Expected output
    1
    
  3. Example 3

    Input
    R 2
    X
    X
    
    Expected output
    2