This page is still under construction.

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

Fixing Codes

Time limit1sMemory limit128 MB

Summary
Given a prefix-free code and a new binary string, find the minimum total number of bits to append so the whole multiset becomes prefix-free again.
Level

Hard8 of 10

Topics
Greedy, Tree, DFS, Bit manipulation
Solved
No attempts yet

Problem

A binary string is a string over the alphabet {0,1}\{0, 1\}. A code is a multiset of binary strings (the same string may appear any number of times). A code is a fixed code if none of its strings is a prefix of another string in it.

A code A={a1,a2,…,an}A = \{a_1, a_2, \ldots, a_n\} is extended to a code B={b1,b2,…,bn}B = \{b_1, b_2, \ldots, b_n\} if aia_i is a prefix of bib_i for every 1≤i≤n1 \le i \le n. The cost of this extension is ∑i=1n(∣bi∣−∣ai∣)\sum_{i=1}^{n} (|b_i| - |a_i|), where ∣x∣|x| is the length (number of characters) of string xx.

You are given a fixed code CC and a new binary string ss. Find the minimum cost needed to extend C∪{s}C \cup \{s\} into a fixed code. In other words, append the fewest possible bits to zero or more of the strings in C∪{s}C \cup \{s\} so that the whole collection becomes a fixed code.

Input

The first line contains an integer tt (1≤t≤201 \le t \le 20), the number of test cases. Each of the next tt lines contains one or more binary strings separated by spaces. Each line has at most 41 strings, and every string has length at most 40. On each line the last string is the new incoming string ss, and the remaining strings form the fixed code CC for that test case.

Output

For each test case, print the minimum cost to extend C∪{s}C \cup \{s\} into a fixed code on its own line.

Examples1

  1. Example 1

    Input
    2
    001 01 00
    000 001 010 011 100 101 110 1
    
    Expected output
    1
    2