This page is still under construction.

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

Tournament

Time limit1sMemory limit128 MB

Summary
Compute the chance that two named entrants meet in a knockout bracket with random seeding and even match odds.
Level

Medium7 of 10

Topics
Probability, Tree, Combinatorics
Solved
No attempts yet

Problem

A martial arts tournament is held in a certain city. NN competitors take part, two of whom are brothers: Olek and Felek.

Every match is fought between two competitors and has exactly one winner, who stays in the tournament, while the loser is eliminated. The order of matches is fixed before the tournament by a "tournament tree". The picture below shows an example tournament tree for four competitors: competitors "start" in the yellow fields, and the green fields are matches.

Example tournament tree for four competitors

At the start of the tournament the competitors are drawn to the starting positions uniformly at random, so every assignment of competitors to the yellow fields is equally likely.

This year the field is so even that you should assume every match is won with equal probability (12\frac{1}{2}) by each of its two competitors.

Compute the probability that at some point during the tournament the brothers Olek and Felek fight each other.

Input

The first line contains the number of test sets ZZ (1≤Z≤51 \le Z \le 5). The descriptions of the sets follow.

Each set begins with a line containing an integer NN (2≤N≤10002 \le N \le 1000), the number of competitors. The next N−1N - 1 lines describe the tournament matches, numbered from 11 to N−1N - 1, one match per line.

Each match description is two strings separated by a single space; each string names one of the two competitors in that match:

  • Z<k> (for example Z1, Z4, with 1≤k≤N1 \le k \le N) is the competitor placed at starting position kk.
  • P<k> (for example P1, P4, with 1≤k≤N−11 \le k \le N - 1) is the winner of match number kk.

The input always describes a valid tournament tree: every starting position feeds exactly one match, and the winner of every match except one (the final) feeds exactly one later match.

Output

For each set, print on its own line the probability that Olek and Felek fight each other, rounded to exactly four digits after the decimal point, rounding half up (for example, 0.5000).

Examples3

  1. Example 1

    Input
    1
    4
    P2 Z4
    P3 Z1
    Z2 Z3
    
    Expected output
    0.5000
    
  2. Example 2

    Input
    1
    2
    Z1 Z2
    
    Expected output
    1.0000
    
  3. Example 3

    Input
    1
    8
    Z1 Z2
    P1 Z3
    P2 Z4
    P3 Z5
    P4 Z6
    P5 Z7
    P6 Z8
    
    Expected output
    0.2500