CF BUDDY
← Problems·

1950G · Shuffling Songs

1900 · bitmasks, dfs and similar, dp

Problem: Vladislav has a playlist consisting of nn songs, numbered from 11 to nn. Song ii has genre gig_i and writer wiw_i. He wants to make a playlist in such a way that every pair of adjacent songs either have the same writer or are from the same genre (or both). He calls such a playlist exciting. Both gig_i and wiw_i are strings of length no more than 10410^4.

It might not always be possible to make an exciting playlist using all the songs, so the shuffling process occurs in two steps. First, some amount (possibly zero) of the songs are removed, and then the remaining songs in the playlist are rearranged to make it exciting.

Since Vladislav doesn't like when songs get removed from his playlist, he wants the making playlist to perform as few removals as possible. Help him find the minimum number of removals that need to be performed in order to be able to rearrange the rest of the songs to make the playlist exciting.

Input Format: The first line of the input contains a single integer tt (1t10001 \le t \le 1000) — the number of test cases. The description of test cases follows.

The first line of each test case contains a single integer nn (1n161 \le n \le 16) — the number of songs in the original playlist.

Then nn lines follow, the ii-th of which contains two strings of lowercase letters gig_i and wiw_i (1gi,wi1041 \leq |g_i|, |w_i| \leq 10^4) — the genre and the writer of the ii-th song. Where gi|g_i| and wi|w_i| are lengths of the strings.

The sum of 2n2^n over all test cases does not exceed 2162^{16}.

The sum of gi+wi|g_i| + |w_i| over all test cases does not exceed 41054 \cdot 10^5.

Output Format: For each test case, output a single integer — the minimum number of removals necessary so that the resulting playlist can be made exciting.

Note: In the first test case, the playlist is already exciting.

In the second test case, if you have the songs in the order 4,3,1,24, 3, 1, 2, it is exciting, so you don't need to remove any songs.

In the third test case, you can remove songs 4,5,6,74, 5, 6, 7. Then the playlist with songs in the order 1,2,31, 2, 3 is exciting.

Sample Cases

Case 1

Input

4
1
pop taylorswift
4
electronic themotans
electronic carlasdreams
pop themotans
pop irinarimes
7
rap eminem
rap drdre
rap kanyewest
pop taylorswift
indierock arcticmonkeys
indierock arcticmonkeys
punkrock theoffspring
4
a b
c d
e f
g h

Output

0
0
4
3

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback