Series / Parallel Resistor Circuits#532

Series / Parallel Resistor Circuits

1 second
64 megabytes
Hard

A series/parallel resistor circuit is shown here.

The resistance value is given next to each resistor. Connection points (wires connecting two or more resistors together) are denoted by an uppercase letter. and are reserved for the names of the connection points which are the endpoints of the circuit. Our goal is to calculate the equivalent resistance of the circuit (that is, the equivalent resistance between and ).

Within the circuit, a resistor can be specified by a triple consisting of the connection points at either endpoint, and the resistance. For example, the resistor labelled "" can be specified as either (C, D, 9) or (D, C, 9). A circuit specification is the set of all such resistor specifications.

A pair of resistors is in series if either of their endpoints share a connection point that is not used by any other resistor (for example, the resistors labelled "" and "" are both connected to , which is not connected to anything else). Such resistors can be replaced by an equivalent resistor whose resistance is the sum of the replaced resistors ( in this example).

A pair of resistors is in parallel if both their endpoints share the same connection points (for example, the resistors labelled "" and "" are both connected to and ). Such resistors can be replaced by an equivalent resistor whose resistance is the inverse of the sum of the inverses of the two resistor values, \left((1/3 + 1/10)^{-1} = 2.307692\right) in this example.

The equivalent resistance of a well-formed series-parallel resistor circuit can be determined by successively replacing a series or parallel resistor pair with a single equivalent resistor, until only one remains.

Not all circuits can be decomposed into series and parallel components. The Wheatstone Bridge, shown here, is a classic example of a circuit that is not considered a well-formed series-parallel resistor circuit.

Input

There will be multiple circuit specifications. The first input line for each circuit specification is an integer (N < 1000), the number of resistors in the circuit. This is followed by lines, each being a resistor specification in the form: , where and are uppercase letters, and is a positive integer resistance (r < 100). The equivalent resistance is never greater than .

A circuit with N = 0 indicates the last circuit and should not be processed.

Output

For each circuit, if the circuit is well formed and reduces to a single equivalent resistance between and , print the equivalent resistance of the circuit from to , rounded to decimal places. If the circuit is not well formed, or if there is no equivalent resistance between and , simply print the number "-1.000". There should be no blank lines between outputs.

Examples

Example 1

Loading
Loading