We are given: Milly loves chocolates. Land has N rooms, each room has some chocolates (brands). Possibly multiple same brand in a room. She eats all chocolates in a room when she enters. She wants to eat at least K distinct branded chocolates at least once. We need minimum number of rooms to visit to achieve at least K distinct brands. If impossible, print -1.
Constraints: T up to 3, N <= 16, K <= 40, P <= 10, brand string length <=10. So N is small (max 16). K up to 40. But number of distinct brands across rooms can be up to maybe N*10 = 160. So we need to select a subset of rooms to minimize number visited while covering at least K distinct brands. This is a classic set cover problem (minimum number of sets to cover at least K elements). N is only 16, so we can use bitmask DP over subsets: for each subset of rooms, compute number of distinct brands covered. Then find minimal size subset with coverage >= K.
We need to parse input: for each test case, first line N and K. Then N lines: each starts with P, then P strings (brand names). Note that there can be multiple same brand within a room, but we treat it as one brand presence: eating all chocolates gives you that brand at least once, duplicates don't matter for distinctness. So we can treat each room as a set of distinct brands present.
So algorithm: For each test case:
- Read N, K.
- For i in [0..N-1]: read line, parse integer P, then P strings. Build a set of brands for that room (e.g., using Python set). Possibly store as list of sets.
- Then we need to compute coverage of any subset. Since N <=16, we can precompute coverage mask? But brands are strings, not bit indices. Could map each brand to an integer id. Then we can represent each room's set as a bitmask over up to M distinct brands (M <= N*10 <= 160). That would fit in an integer? Python's arbitrary ints can handle 160 bits, so we can do bitmask for brands. That would allow fast union via bitwise OR. However, we need to count bits set to check coverage >= K. That can be done with bit_count() in Python 3.8+.
But there is also K up to 40, which is small. We could also compute number of distinct brands per subset by merging sets. But bitmask is efficient.
Steps:
-
Scan all rooms, collect all distinct brands across all rooms. Build a dictionary mapping brand to index (0..M-1).
-
For each room i, compute a bitmask: an integer where bit at index idx is set if brand present.
-
Then iterate over all subsets from 0 to (1<<N)-1. For each subset, compute the union bitmask. To avoid O(2^N * N) maybe we can use DP to compute union incrementally: dp[mask] = dp[mask without LSB] OR mask_room[lsb_index]. But since N is only 16, 2^16 = 65536, and for each we can compute union by iterating bits of mask (max 16). That's fine. 65536 * 16 = ~1M operations per test case, plus counting bits, all good. Or we can do DP: for mask, let lsb = mask & -mask, index = bit position, then union[mask] = union[mask ^ lsb] | room_mask[index]. This is O(2^N). Good.
-
After having union[mask], compute popcount (number of distinct brands covered). If >= K, update answer = min(answer, popcount of mask (i.e., number of rooms visited)). The number of rooms visited is the number of bits set in mask.
-
If answer remains infinity, print -1 else print answer.
Edge cases: If K=0? But constraints say K >= 1. So ignore.
Complexities: fine.
Now sample: N=3, K=2. Rooms: 1: KITKAT; 2: FIVESTAR KITKAT; 3: KITKAT PERK. Distinct brands: KITKAT, FIVESTAR, PERK -> 3. Subsets: mask size 1: each room covers 1 brand except room2? Actually room1 covers 1, room2 covers 2 (FIVESTAR and KITKAT), room3 covers 2 (KITKAT, PERK). So min rooms=1 (room2 or room3). Output 1.
Ok.
Now we need to handle multiple test cases T.
Implementation details: Input reading. First line T. Then for each test case: read line with N and K. Then loop N times: each line may have variable length. We can use input().split() to read tokens. But careful: first token is integer P. Then next P tokens are brand names. So we can read whole line, split, first element is P, then next P strings. But there might be more tokens if brand names contain spaces? Brand names are strings without spaces (length <=10). So simple split is fine.
Alternatively use sys.stdin.
Now caution: There might be blank lines? Usually not.
So we will implement.
Now one more point: The brand strings may appear in multiple rooms. Using mapping to ints works.
Let's code.
But think about the size: M <= 160. Use Python's int for bitmask; compute popcount via bin(mask).count('1') or mask.bit_count() (Python 3.8+). We'll use mask.bit_count().
Now DP: union = [0] * (1<<N). union[0] = 0. For mask from 1 to (1<<N)-1: get lsb = mask & -mask, index = (lsb.bit_length() - 1). Then prev = mask ^ lsb, union[mask] = union[prev] | room_masks[index].
Then ans = large. For mask from 1 to ...: if union[mask].bit_count() >= K: ans = min(ans, mask.bit_count()).
Print ans if not INF else -1.
But we can also break early for small sizes? Not needed.
Now note: N <= 16, so 1<<N at most 65536, union list of ints of length 65536, fine.
Now test with sample.
Potential pitfalls: Because K can be larger than total distinct brands. In that case, impossible. So if total distinct brands across all rooms < K, answer -1. But we will detect via mask all rooms: union[(1<<N)-1].bit_count() < K => answer stays INF, so we print -1. Good.
But we could short-circuit: compute total distinct brands across all rooms, if < K, print -1 and skip DP? That's optional.
Now we need to consider that each room may have duplicate brands: our set handles that.
Now we must consider reading: N lines each start with P and then P brand strings. We need to store them as sets.
Implementation steps:
For each test case:
-
read line (maybe with trailing newline). Use input().split() -> tokens. tokens[0] = N, tokens[1] = K.
-
N = int(tokens[0]); K = int(tokens[1])
-
Initialize list brands_per_room = [] (list of sets)
-
Also maintain a set all_brands = set()
-
For i in range(N):
line = input().split()
P = int(line[0])
brands = line[1:] # should have length P
Could validate len(brands) == P but trust input.
room_set = set(brands)
brands_per_room.append(room_set)
all_brands.update(room_set)
-
If len(all_brands) < K: print(-1) and continue? But careful: maybe some rooms combined could still be less? That's total distinct brands across all rooms. So if total < K, then impossible. So we can output -1 and skip DP to save time. But not needed.
-
Map brands to indices:
brand_to_idx = {brand: idx for idx, brand in enumerate(all_brands)} # but all_brands is a set, order not stable but fine.
M = len(all_brands)
-
Compute room_masks = []
for room_set in brands_per_room:
mask = 0
for brand in room_set:
mask |= (1 << brand_to_idx[brand])
room_masks.append(mask)
-
DP:
total_masks = 1 << N
union = [0] * total_masks
For mask from 1...
for mask in range(1, total_masks):
# isolate lowest set bit
lsb = mask & -mask
idx = (lsb.bit_length() - 1) # since lsb is power of two
prev = mask ^ lsb
union[mask] = union[prev] | room_masks[idx]
-
ans = N+1 (since maximum rooms N, but we can set to N+1)
for mask in range(1, total_masks):
if union[mask].bit_count() >= K:
ans = min(ans, mask.bit_count())
-
if ans <= N: print(ans) else print(-1)
Edge Cases:
- K=0? Not allowed.
- N=0? Not allowed as N>=1.
But what if we use union[0]=0. fine.
Now test with sample.
We need to consider that N <= 16, but we need to be careful about reading: The input lines may have leading/trailing spaces. But split() handles.
Now time complexity: for T <= 3, max N=16, so fine.
Potential memory: union list of 65536 ints, each maybe a few bytes, fine.
Alternative approach: Since K <= 40, we could also use meet-in-the-middle or other techniques, but not needed.
Thus solution is straightforward.
Now, we should output for each test case the required answer.
Now, for large test case N=16, M up to 160, mask up to 2^N = 65536, DP is fine.
But be careful: brand index up to maybe 159, so shift 1 << idx may be up to 2^159 which is a huge integer but Python supports big ints. The bit_count operation on large ints is fine. But we need to ensure that the mask operations are efficient. Should be fine.
But we might consider using Python's integers for union; they are arbitrary precision. For 160 bits, it's fine.
Now potential pitfalls: When we compute union[mask] = union[prev] | room_masks[idx], we are ORing two ints. That's fine.
Now we should also consider: we can break early if we find a solution of size 1, etc. But not needed.
Now note: the problem states: "print the minimum number of rooms she must visit to eat at least those K distinct brands at least once." So answer is the number of rooms, not which ones.
Ok.
Now test with sample.
We'll simulate:
N=3, K=2. all_brands: KITKAT, FIVESTAR, PERK (order maybe). Suppose mapping: KITKAT:0, FIVESTAR:1, PERK:2.
Room masks: room0: {KITKAT} => 1<<0 = 1
room1: {FIVESTAR, KITKAT} => (1<<1)|(1<<0) = 3
room2: {KITKAT, PERK} => (1<<0)|(1<<2) = 5
DP:
mask 1 (001): union = room0 mask =1, bit_count=1 <2.
mask 2 (010): union = room1 mask =3, bit_count=2 >=2 -> ans=1 (mask.bit_count()=1)
mask 3 (011): union = union[2] | room0? Actually lsb of 3 is 1, idx0, prev=2, union[2]=3 OR room0=1 => 3, bit_count=2, mask.bit_count()=2 -> ans stays 1.
mask 4 (100): union = room2=5, bit_count=2 -> ans=1 (mask.bit_count=1) -> ans=1
So final ans=1. Print 1. Good.
Now test case where impossible: Suppose N=2, K=3, rooms: 1 brand each, distinct 2 total => total < K. DP will compute all subsets, none have coverage >=3, ans remains INF, output -1.
Now we should ensure that we read the first line of input correctly: First line T. Then for each test case, read line with N K. But there might be blank lines? Usually not.
Let's write code.
I'll provide final solution in Python.
Potential improvement: Use sys.stdin.read to read all tokens and parse quickly. But not needed.
But caution: When reading input, sometimes lines after first may have extra spaces. Use .split().
Will implement solve() function.
Now about handling multiple test cases: After reading T, loop T times.
Now we should output each answer in separate line.
Now code:
import sys
def solve():
data = sys.stdin.read().split()
# but careful: We need to parse structured: first token T, then for each test case: N, K, then for each room: P and then P brand strings.
# Using token list is simpler: but we need to know lengths.
# Let's do iterative index.
it = iter(data)
T = int(next(it))
out_lines = []
for _ in range(T):
N = int(next(it))
K = int(next(it))
rooms = []
all_brands_set = set()
for i in range(N):
P = int(next(it))
brands = [next(it) for __ in range(P)]
room_set = set(brands)
rooms.append(room_set)
all_brands_set.update(room_set)
# If total distinct brands less than K, impossible
if len(all_brands_set) < K:
out_lines.append("-1")
continue
# Map brands to indices
brand_to_idx = {brand: idx for idx, brand in enumerate(all_brands_set)}
room_masks = []
for room_set in rooms:
mask = 0
for brand in room_set:
mask |= 1 << brand_to_idx[brand]
room_masks.append(mask)
total_masks = 1 << N
union = [0] * total_masks
# DP
for mask in range(1, total_masks):
lsb = mask & -mask
idx = (lsb.bit_length() - 1)
prev = mask ^ lsb
union[mask] = union[prev] | room_masks[idx]
ans = N + 1
for mask in range(1, total_masks):
if union[mask].bit_count() >= K:
rooms_used = mask.bit_count()
if rooms_used < ans:
ans = rooms_used
if ans == N + 1:
out_lines.append("-1")
else:
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
But we need to ensure that reading with sys.stdin.read().split() is fine. The input format: T then each test case: line with N K. Then each room line: P followed by P brand strings. All tokens are separated by whitespace (space or newline). So reading all tokens is safe. But careful: brand names may be repeated? No issue. So it's fine.
One subtlety: The lines may contain extra spaces, but split handles.
We should also consider that P can be up to 10 and brand strings length up to 10, but no special characters. So fine.
Now check with sample input:
Input:
1
3 2
1 KITKAT
2 FIVESTAR KITKAT
2 KITKAT PERK
Tokens: "1", "3", "2", "1", "KITKAT", "2", "FIVESTAR", "KITKAT", "2", "KITKAT", "PERK". This will parse correctly: T=1, then test case: N=3, K=2. Then first room: P=1, brand "KITKAT". second: P=2, brands "FIVESTAR", "KITKAT". third: P=2, brands "KITKAT", "PERK". Works.
Now answer: we compute ans=1. Output "1". Good.
Now test with custom:
T=1, N=1, K=1, room: 1 BRAND -> ans=1? Should be 1. Our code: all_brands_set size=1 >=1; room_mask = 1<<0=1; DP: mask 1 -> union[1] = union[0]|room_mask = 1, bit_count=1 >=1, ans = mask.bit_count()=1 => print 1. Good.
Now test with impossible: T=1, N=2, K=3, rooms: 1 A; 1 B. all_brands_set size=2 <3 => output -1. Good.
Now test with N=16, all rooms have up to 10 brands, M up to 160, DP loops 65536, each step few bit operations, fine.
Now check the bit_length method for idx: lsb is a power of two, bit_length() returns position of highest set bit +1. For lsb = 1 (binary 1), bit_length=1 -> idx =0. For lsb=2 (10b), bit_length=2 -> idx=1. For lsb=4 (100b), bit_length=3 -> idx=2. So works.
Alternative: idx = (lsb.bit_length() - 1) or use (lsb.bit_length() - 1). Good.
Now time complexity: O(T * (2^N + N*P + M)). Fine.
Now memory: union list of 2^N ints, each maybe ~ 160 bits => 20 bytes? 65536*20 ~1.3 MB, fine.
Now we should consider if there is any other nuance: The problem says "at least K distinct branded chocolates at least once." So if K is 0, answer 0, but K >=1. So fine.
Now we are ready to output solution.
But wait, note: There is possibility that P can be 0? Constraint says 1 ≤ P ≤ 10, so P >=1. So each room has at least 1 chocolate.
Now check if any brand appears multiple times within a room, we treat as set. That's correct.
Now we also need to handle the scenario where the same brand may appear in multiple rooms. Our union bitmask correctly ORs.
Now might there be a scenario where K is > M (total distinct brands across all rooms) but we output -1. We covered that.
Now corner case: N=0? Not possible.
Now the solution is complete.
But there is one more nuance: The input states: "First line of the input will contain a integer T (number of test cases). Then for every test case there will be one line containing the values of N and K separated by a space. Now each of the next N lines will first have a value P then P space separated strings denoting the names of the brands." That suggests that the N lines are separate lines. Using token parsing as we did is okay; it doesn't care about line boundaries.
Now about output: For each test case, print the answer.
Now we can finalize.
One more thought: Since N <= 16, could also solve using bitmask enumeration of rooms and using union by bitset. But we already did.
Now we can present final answer.
Now I'd like to test with a more complex scenario: Suppose N=4, K=3, brands: room0: A B, room1: B C, room2: C D, room3: D A. Total distinct = 4. Minimal rooms to cover 3 distinct could be 2? For example rooms 0 and 2 cover A,B and C,D? Actually room0: A,B; room2: C,D => coverage A,B,C,D (4) >=3, so 2 rooms. Or room0 and room1: A,B,C => 2 rooms. So answer 2. Our DP will find.
Now test with K=4: need all rooms? Actually union of rooms 0 and 2 covers all 4? Yes 0+2 => A,B,C,D covers all 4, so answer 2. Good.
Now code appears correct.
Now we need to ensure that when we compute union[mask] for mask=0, it's 0. That's fine.
Now check if there is any off-by-one: For mask with one bit set, we compute union[prev] where prev is mask ^ lsb, which is 0. So union[0]=0 OR room_mask = correct.
Now answer initially N+1. If we never update, output -1; else output ans.
Now final code.
Potential performance: For each test case, we do DP for mask from 1..2^N-1, but we might break early if we find ans=1? But we can just compute everything, as 2^16 is small.
Now let's write final answer.
But wait: Are we sure that we need to consider "at least K distinct branded chocolates" meaning exactly K or at least K? It says "at least K distinct branded chocolates at least once." So it's at least K.
Now there's also note: "Once she enters a particular room, she will eat all of the chocolates available in that room." So she cannot partially eat. So our set cover approach is correct.
Now we should also note that the brand strings could be case-sensitive? Probably as given. We treat them as strings.
Now finalize.
But there might be a twist: The problem might ask "minimum number of rooms she must visit" implying she can visit any order, but order doesn't matter.
Now I'll produce final solution.
Before final answer, consider if we could also use brute force search over subsets ordered by size, and break as soon as coverage >=K. Since N <=16, we could generate subsets of increasing size and compute union on the fly. That would be more efficient if answer is small. But we can still do full DP.
But let's think: If we generate subsets in increasing size order, we might need to compute union for each. But we need to compute union quickly. Could also use precomputed room masks and then for each subset compute union by iterating bits, but that's okay. However, DP we already compute union for all masks, which might be unnecessary if answer is small. But since N is small, it's fine.
Now I'll consider if there's any more optimal solution using meet-in-the-middle for N up to 30, but N is 16 so DP is fine.
Now implement.
One more thought: Could we use Python's built-in frozenset? Not needed.
Now final answer code.
Now provide explanation and code.
Will output answer accordingly.
But note: The problem might be from a contest, the sample output is 1. Our solution yields that.
Now verify a scenario: N=16, K=40, M maybe 160, DP fine.
Now I'm confident.
Edge: If all_brands_set size is huge (like 160) but K is 40, we might still be able to cover 40 with few rooms. Our DP works.
Now finalize.
One more nuance: Our method uses bitmask of brands; but if M > 63, Python integers still fine.
Now consider if M > 1000, but maximum M = N * P <= 16 * 10 = 160, so fine.
Now ready.
But wait, brand names length up to 10, but they could be repeated across rooms. Our mapping uses set of all brands, which size <= 160.
Now final code.
Now we need to output each answer in new line.
Now after writing code, we'll test with sample.
Now I think that's all.
Potential mistake: In DP, we computed union[mask] = union[prev] | room_masks[idx]. But this relies on union[prev] already computed. Since we are iterating mask from 1 upwards, we need to ensure that for each mask, the prev mask (mask ^ lsb) is less than mask, which is true because lsb is non-zero. And we compute in increasing numeric order, but mask ^ lsb is always less than mask? Not necessarily if we go numeric order, mask ^ lsb could be larger than mask? Let's check: mask = 5 (101), lsb = 1 (001), prev = 4 (100). 4 < 5, ok. mask=6 (110), lsb=2 (010), prev=4 (100) < 6. mask=3 (011), lsb=1, prev=2 < 3. mask=7, lsb=1, prev=6 < 7. In general, removing the lowest set bit reduces the number, so the resulting number is less than mask. So since we iterate from 1 to max inclusive, by the time we get to mask, we have already computed all numbers less than mask, including prev. So it's safe.
Now ensure that union list is initialized with zeros for mask 0. Good.
Now answer is found.
Now let's consider if we could get answer 0? Only if K=0, but K>=1.
Now we are done.
Now final solution.
But before final answer, check if there is any oversight about "minimum number of rooms she must visit to eat at least those K distinct brands at least once." There is no restriction that she cannot revisit rooms. But since she eats all chocolates when she enters, revisiting doesn't add new distinct brands, so it's unnecessary.
Now produce final answer.
Now we will output explanation and code.
Now I'll write the answer. ```python
import sys
def solve() -> None:
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
k = int(next(it))
# read the N rooms
rooms = []
all_brands = set()
for _ in range(n):
p = int(next(it))
brands = [next(it) for __ in range(p)]
room_set = set(brands)
rooms.append(room_set)
all_brands.update(room_set)
# Quick impossibility check
if len(all_brands) < k:
out.append("-1")
continue
# Map each brand to a unique integer index
brand_to_idx = {brand: idx for idx, brand in enumerate(all_brands)}
room_masks = []
for room_set in rooms:
mask = 0
for brand in room_set:
mask |= 1 << brand_to_idx[brand]
room_masks.append(mask)
total_masks = 1 << n
union = [0] * total_masks # union[mask] = bitmask of brands covered by the subset
# DP over subsets
for mask in range(1, total_masks):
lsb = mask & -mask # lowest set bit
idx = lsb.bit_length() - 1 # room index of that bit
prev = mask ^ lsb # subset without that room
union[mask] = union[prev] | room_masks[idx]
ans = n + 1
for mask in range(1, total_masks):
if union[mask].bit_count() >= k:
rooms_used = mask.bit_count()
if rooms_used < ans:
ans = rooms_used
out.append(str(ans) if ans <= n else "-1")
sys.stdout.write("\n".join(out))
if name == "main":
solve()