A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.
The participants are offered m problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles.
Gena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer.
Input
The first line contains three integers n, m and b (1 ≤ n ≤ 100; 1 ≤ m ≤ 20; 1 ≤ b ≤ 109) — the number of Gena's friends, the number of problems and the cost of a single monitor.
The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend. The 2i-th line contains three integers xi, ki and mi (1 ≤ xi ≤ 109; 1 ≤ ki ≤ 109; 1 ≤ mi ≤ m) — the desired amount of money, monitors and the number of problems the friend can solve. The (2i + 1)-th line contains mi distinct positive integers — the numbers of problems that the i-th friend can solve. The problems are numbered from 1 to m.
Output
Print the minimum amount of money Gena needs to spend to solve all the problems. Or print -1, if this cannot be achieved.
Examples
Input
2 2 1
100 1 1
2
100 2 1
1
Output
202
Input
3 2 5
100 1 1
1
100 1 1
2
200 1 2
1 2
Output
205
Input
1 2 1
1 1 1
1
Output
-1
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to parse problem statement: There are n friends. Each friend i has: xi (cost rubles), ki (minimum number of monitors required to hire this friend), and mi (number of problems he can solve) and a list of those problems (size mi). Gena can buy monitors at cost b per monitor. Initially, there are no monitors. He can buy any number of monitors (integer) and then hire any subset of friends (paying each xi) subject to: For each hired friend, the number of monitors Gena has must be at least ki. (Presumably monitors are purchased once and common; they are not per friend). So he buys a certain number of monitors M (non-negative integer). Then any friend with ki <= M can be hired. He pays total = M * b + sum_{i hired} xi. He must cover all m problems (i.e., union of problems solved by hired friends must be all problems 1..m). He wants to minimize total cost.
We need to find minimal total cost or -1 if impossible.
Constraints: n ≤ 100, m ≤ 20, b up to 1e9, xi, ki up to 1e9. So m is small (20) which suggests state DP over problem subsets (bitmask). Also n ≤ 100, but xi and ki large, so need to handle efficiently.
Observations: The monitors cost is b per monitor, and monitors are global. For a given M (number of monitors purchased), we can only hire friends with ki ≤ M. The total cost = Mb + sum of xi for hired friends covering all problems. For a given M, we want minimal sum of xi needed to cover all problems using only friends with ki ≤ M. This is like a set cover with costs, but m is small (20), so we can DP over subsets: compute dp[mask] = minimum total xi cost to achieve mask (set of problems solved) using only friends with ki ≤ M. Since n up to 100, we can do DP by iterating over friends and updating dp (like knapsack over subsets). That's O(n * 2^m) per M. But M can be large (ki up to 1e9). However, the ki values are only from the friends. The relevant M values are only the distinct ki thresholds (and maybe 0). Because if M is between two consecutive distinct ki values, the set of allowed friends is same as for the lower ki. So the minimal cost for covering all problems as a function of M will be constant on intervals [k_j, k_{j+1} - 1] (where k_j sorted). So we only need to evaluate M equal to each distinct ki among friends (and maybe M=0). But careful: If we choose M less than all ki, no friend is allowed, impossible. As M increases, more friends become available, possibly decreasing sum xi needed. So total cost = Mb + f(M), where f(M) = minimum sum xi to cover all problems using friends with ki <= M (or infinity if impossible). Since b is positive, f(M) is non-increasing as M increases (more friends available, can only reduce cost or keep same). So total cost might have a convex shape? Not necessarily monotonic? M*b is increasing, f(M) decreasing. So overall can have a minimum at some M among candidate thresholds.
We can proceed: sort friends by ki. Then consider thresholds: the distinct ki values (maybe also consider M=0 but then f(0) is infinite unless no problems needed? m>=1 so impossible). For each possible M = each distinct ki (or maybe also consider M= some ki-1? But then same set of allowed friends as previous threshold? Actually if M is just below next ki, the set of allowed friends is those with ki <= M, which is exactly those with ki <= previous threshold if there is no friend with ki in (prev, M]. So the set only changes when M crosses a ki. So we only need to evaluate M at each ki value (including possibly M = max(ki) if needed). However, we might also consider not buying any monitor if we have friends with ki=0? But ki >=1 per constraints (1 ≤ ki ≤ 1e9). So minimal ki is at least 1. So we need to buy at least min ki among friends used. So M must be at least max of ki of hired friends. So we can treat M = max(ki) among hired subset. But we can also buy more monitors than needed (if b>0, extra monitors would increase cost, never beneficial unless needed for some friend). So we would never buy more monitors than the maximum ki among the friends we hire. Because buying extra monitors adds cost without benefit. But wait: if we hire some friends, M must be at least max_{i hired} ki. Buying exactly that max is optimal. Because if we buy more, total cost increases by b per extra monitor, and f(M) doesn't change (since friends with ki > max hired not used). So we can restrict to M equal to the maximum ki among hired friends. So we only need to consider M being the ki of some friend (the max in the hired set). Thus we can iterate over possible values of M = each friend's ki (or maybe combination? The max among hired set is some ki among those hired). So we can consider each friend as the one with max ki in the hired set? But there may be multiple friends with same ki. In any case, the M we choose can be any ki that is >= all hired friends' ki. But we can always choose M = max ki among hired friends. So we can think of each candidate M as a threshold, and we compute min xi cost using any subset of friends with ki <= M, possibly also using friends with exactly M as the highest. Then total = Mb + cost. So we only need to compute f(k) for each distinct k (sorted ascending) and then total(k) = kb + f(k). Then answer = min total(k) over all k such that f(k) finite.
But caution: Could it be optimal to set M larger than the max ki among hired friends, if buying extra monitors allows to hire additional friend with higher ki? That is, we want to use some friends with high ki, so M must be at least that high ki. So we will consider M = that high ki. So it's covered.
Thus algorithm:
Read n,m,b.
For each friend i, store xi, ki, and a bitmask of problems he can solve (mi bits).
Sort friends by ki ascending (or not necessarily; we will process in order of increasing ki to build DP gradually). Because as we increase threshold, we add new friends. This is like DP incremental: We maintain dp[mask] = minimum xi cost to achieve mask using only friends processed so far (i.e., those with ki <= current threshold). Initially, dp[0]=0, others = INF. As we add a friend (xi, mask), we can update dp: for each mask2, dp[mask2 | mask] = min(dp[mask2 | mask], dp[mask2] + xi). This is like a knapsack over subsets.
But we need to compute total cost for each distinct ki (the threshold). As we go through friends sorted by ki, after processing all friends with ki <= current_k (i.e., after adding all friends with that ki value), we have dp for that threshold. Then compute total = current_k * b + dp[fullMask] (where fullMask = (1<<m)-1). Take the min across thresholds.
Potential issues: Since b is large (1e9) and ki up to 1e9, multiplication may overflow 64-bit? 1e9 * 1e9 = 1e18, which fits in 64-bit signed? 2^63-1 ~9.22e18, so 1e18 fits. Use long long.
Also xi up to 1e9, sum of up to n friends could be up to 1e11, which fits in 64-bit as well. So use 64-bit.
Edge Cases: If after processing all friends dp[full] still INF, answer -1.
Now, check examples:
Example 1:
n=2,m=2,b=1
Friend1: x=100, k=1, mi=1, problem2 => mask=010? Actually problem numbers: 2 -> bit 1 (since 1-indexed? Let's set bit for problem j: 1<<(j-1). So mask1 = 1<<1 = 2 (binary 10)
Friend2: x=100, k=2, mi=1, problem1 => mask2 = 1<<0 = 1 (binary 01)
Sorted by k: friend1 (k=1), friend2 (k=2). Process friend1: dp[0]=0, after update: dp[2]=100. fullMask=3. At k=1: total = 11 + dp[3]? dp[3] is INF (since not covered). So ignore. Then process friend2: after adding friend2, dp[1]=100? Actually start from previous dp: dp[0]=0, dp[2]=100. Update with friend2: from dp[0] -> dp[1]=100; from dp[2] -> dp[3]=200. So dp[3]=200. At k=2: total = 21 + 200 =202. Answer=202 matches.
Example 2:
n=3,m=2,b=5
Friend1: x=100,k=1,mi=1, problem1 => mask=01
Friend2: x=100,k=1,mi=1, problem2 => mask=10
Friend3: x=200,k=1,mi=2, problems1,2 => mask=11
Sorted all k=1. Process all three: After processing friend1: dp[1]=100. After friend2: from dp[0]->dp[2]=100; from dp[1]->dp[3]=200. After friend3: from dp[0]->dp[3]=200; from dp[1]->dp[3] min(200,100+200=300) stays 200; from dp[2]->dp[3] min(200,100+200=300) stays 200; etc. So dp[3]=200. At threshold k=1: total=1*5+200=205. That's answer. But note there is also possibility of using only friend3? cost 200, monitors 1, total=5+200=205 same. Or friends1+2 cost 200 total 5+200=205. So correct.
Example 3:
n=1,m=2,b=1
Friend: x=1,k=1,mi=1, problem1 => mask=01. After processing: dp[full]=INF, answer -1. matches.
So algorithm works for examples.
But is there any nuance: The monitors are required per friend: "the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors". That means if Gena buys M monitors, he can hire any friend with ki <= M. So our interpretation is correct.
We also need to consider possibility that we might want to not hire any friend with highest ki but still buy more monitors than needed to maybe allow hiring of a different set? But we only consider M as the max ki among hired friends because if we buy more monitors than the max ki of hired friends, it's wasteful. However, what if there is a scenario where we could hire a set with lower total xi if we also consider a higher M that allows a friend with a high ki but whose xi is low, and that could reduce the sum xi enough to offset the higher monitor cost? That scenario would involve hiring at least one friend with that high ki, so M must be at least that high ki. So M equals that high ki (or maybe larger). But we can just set M equal to that high ki exactly, not larger. So our method of considering thresholds exactly equal to ki (the max among hired) covers it. But do we need to consider the possibility that we set M to a value that is not equal to any friend's ki, but higher than the max ki among hired friends? That would increase cost with no benefit, so suboptimal. So we can ignore.
Thus the DP approach with sorted friends and evaluating after each distinct ki works.
Implementation details:
Represent mask as integer up to (1<<m)-1, m <=20 so fits in 32-bit int.
dp array size 1<<m, initialize with INF (large number like 1e18). dp[0]=0.
Sort friends by ki ascending.
Iterate over friends in sorted order, while keeping track of current_k (the ki of current friend) and when we encounter a new ki, we could compute total after processing all friends with previous ki? Actually we need to compute total after each distinct ki, because after adding all friends with that ki, we have the best cost using friends up to that ki. But note: The monitors cost uses ki (current threshold) which is exactly the ki we are at. However, we must be careful: Suppose there are friends with the same ki, we need to include them all before computing total for that ki. Because if we compute total after processing only part of friends with that ki, we might miss cheaper combinations that use multiple friends with that same ki. So we should process all friends with same ki, then compute total.
Better: Sort friends by ki. Then iterate i from 0 to n-1, but maintain the dp as we add each friend. At each step after adding all friends with a given ki (i.e., when next friend has different ki or after finishing group), we compute candidate = ki * b + dp[fullMask] (if dp[fullMask] finite) and update answer.
Edge: There might be case where it's possible to cover all problems with friends that have ki less than some threshold, but we might still consider buying monitors exactly equal to that threshold (which is lower than the max ki of used friends? Wait, if we cover all problems using only friends with ki <= some k0, then the max ki among used friends is at most k0. So we could buy M = max_ki_used <= k0. But we might be evaluating at threshold = k0, which may be larger than max_ki_used if there is no friend with ki exactly max_ki_used? Actually since friends have discrete ki values, the maximum ki among used friends is some value among the set of ki of friends used. That value is certainly one of the distinct ki values. So if we evaluate at that exact value (the max ki among used friends), we get the dp that includes at least those friends (since we've added all friends with ki <= that value). But we might also include other friends with lower ki. So dp[full] at that threshold includes that combination. So that total cost (max_ki_used * b + sum xi) will be considered. But note that when we evaluate at a threshold larger than the max_ki_used, we could still use the same combination of friends (since they are allowed). However total would be larger because monitors cost is higher. So not minimal. So it's fine to only evaluate at each distinct ki after adding all friends with that ki. Because the optimal M will be exactly the max ki of the optimal subset. That max ki is one of the ki values (since it's the ki of some friend in the subset). So evaluating at that ki will catch it.
Potential nuance: Could there be a scenario where the optimal subset uses friends with max ki = K, but there are also other friends with ki = K that are not used. But our DP at threshold K includes all friends with ki <= K, so it includes the ones we use, and dp[full] will compute min cost using any subset of those. That min cost might be less than or equal to the cost of the optimal subset. But if the optimal subset uses max ki exactly K, then dp[full] at threshold K will be at most that cost (since it's allowed). However, there might be an even cheaper combination using some friends with ki <= K (maybe also with max ki less than K) that yields lower sum xi but requires M less than K. But then total cost at M=K would be higher because M is larger. So the optimal overall may come from a lower threshold. But we evaluate at all thresholds, so we will capture the best total.
Thus algorithm stands.
Complexities: n up to 100, m up to 20, so 2^m up to 1,048,576. n * 2^m = 100 million ~ 1e8, which might be borderline but likely okay in C++ with optimization (like using loops, not too heavy). But we can also improve: Since we update dp for each friend, we might need to iterate over all masks for each friend. That is O(n * 2^m). For n=100, 2^20=1,048,576 => ~100 million operations, which is okay in C++ if optimized (e.g., using int loops, not too many memory accesses). Python might struggle, but we are doing reasoning for implementation in C++? The problem is from Codeforces? Usually it's C++ but we can still implement in Python? But with m=20, 2^20 ~ 1M, and n=100, operations ~100M, which in Python may be too slow. However, we can try to optimize using list comprehensions, but might still be near limit. But typical Codeforces time limits are for C++ solutions, but Python solutions often need optimized approaches. There is possibility to use bitset or other optimizations, but likely we need to implement in C++ for safety. However, the problem statement didn't specify language; we can provide solution in Python with careful optimization? Let's evaluate: 100 * 1,048,576 = 104,857,600. In Python, iterating over a list of that size and performing min operations might take ~0.5 seconds per 10 million? Actually Python loops are slower; 100 million operations could be several seconds (maybe 4-5 seconds), which might be too high for typical 2-second limit. But we can use PyPy, which is faster for loops? It can handle maybe 100 million simple operations within time? Possibly borderline. However, there are ways to reduce constant factor: Instead of updating dp for each friend with a full mask loop, we can do DP using "OR" transitions. Since we need to compute min cost to achieve each subset, the standard technique for covering sets is to iterate over friends and for each mask from 0 to full, do newmask = mask | friend_mask, dp2[newmask] = min(dp2[newmask], dp[mask] + xi). To avoid overwriting issues, we can either loop mask descending? But OR is not like addition; we cannot do typical in-place update because newmask may be larger than mask, but could also be same or smaller? Actually OR always produces mask >= mask (in sense of bits set). So newmask is always superset of mask. If we iterate masks from 0 to full (increasing order), then when we use dp[mask] that has already been updated with the current friend, we might use the friend multiple times? We must ensure each friend is used at most once. Usually we do for mask from full down to 0 for knapsack where addition, but here OR doesn't have monotonic property with integer order? For bitmask, if we iterate from 0 upward, we might use the friend multiple times inadvertently because we can update a mask then later use that updated dp to update another mask, effectively using the same friend twice. To avoid that, we can either use a temporary dp array copy, or iterate mask from full down to 0? Let's check: If we iterate mask descending (from full to 0), when we consider mask, dp[mask] hasn't been updated yet for this friend if newmask > mask? Actually newmask = mask | friend_mask. Since friend_mask may add bits, newmask >= mask in terms of integer? Not necessarily: e.g., mask = 2 (10), friend_mask=1 (01) => newmask=3 (11) which is larger integer. So if we iterate descending from full to 0, when we are at mask=2, we haven't yet processed mask=3? But we will later process mask=3? However, we want to use the original dp values (before adding this friend) to compute newmask. If we update in-place descending, then when we get to a smaller mask, we might update a larger mask that hasn't been processed yet, but that larger mask will later be processed using the updated value (which includes this friend) and then could further combine with friend again? Let's simulate: dp initially. For each friend, we want to consider adding this friend to any previous subset (i.e., combine with dp[mask] from before this friend). So we need to use dp values from previous state (without this friend) to compute new ones. If we do in-place update, we risk using a dp[mask] that has already been updated by this friend (i.e., we added the friend to some previous mask, producing a new dp[mask]) and then using it to add the friend again, resulting in double counting. So to avoid that, we must ensure that when we compute dp[newmask] = min(dp[newmask], dp_old[mask] + xi). So typical approach is to either use a separate dp_new array (copy of dp) and update, or iterate mask from full down to 0 while using dp values that have not been updated for this friend? In knapsack with addition, we iterate from high to low to avoid using the item multiple times because the recurrence dp[w] = min(dp[w], dp[w - weight] + value) uses earlier dp values. For OR, newmask is always greater or equal in terms of bits, but not necessarily in numeric order. However, if we iterate masks in decreasing order of numeric value, then when we process a mask, we haven't processed any newmask that is greater numerically? Actually if we iterate from full down to 0, then when we process a mask, all masks larger than it (numerically) have already been processed? No, we start from full and go downwards, so we process larger numbers first. Then, when we are at mask, we will compute newmask = mask | f. Since newmask may be larger numerically? Possibly, but if newmask is larger than mask, then we have already processed that newmask earlier (since we are going from high to low). So we would be updating a state that has already been processed in this same iteration, which could cause issues because later we might use that updated state when processing even lower masks? But if we only use dp[mask] (original) and update dp[newmask], but dp[newmask] might have already been "finalized" for this friend? Not really; the typical approach for knapsack where we iterate from high to low works because the recurrence uses dp[w - weight] (a smaller index) and updates dp[w]. Since we go from high to low, dp[w - weight] is still from previous iteration (not updated in this pass) because it's lower index, which we haven't touched yet. In OR case, we are using dp[mask] (maybe smaller numeric) to update dp[newmask] (maybe larger numeric). If we go from high to low, when we are at mask (lower numeric), dp[newmask] (higher numeric) has already been processed; updating it afterwards won't affect any further updates from higher masks because those have been done. But it's fine: we don't need to use the updated dp[newmask] in this pass. The problem is that we might use dp[mask] that has been updated earlier in this pass (i.e., mask might have been updated because it is a newmask from some even smaller mask?). Actually if we process masks from high to low, when we get to a mask, could that mask have already been updated by processing a larger mask? Let's think: Suppose we have two masks: bigMask = 3, smallMask = 2. friend_mask = 1. We start from full (maybe 3). For mask=3, compute newmask = 3|1 = 3 (same). update dp[3] with dp[3]+xi? That could lower it but that's just using friend again, which we want to avoid? Actually it would allow using friend multiple times if dp[3] already includes friend? But we will handle that later. But the key: When we process mask=3, we use dp[3] old? But dp[3] might have been updated earlier in this pass? In descending order, we start with mask=3. It hasn't been updated yet, so we use old value. Then we compute newmask = 3, and update dp[3] in place. This means dp[3] now includes possibly using the friend. Then we go to mask=2. At this point dp[2] is old (not updated yet). We compute newmask = 2|1 = 3. We compare dp[3] (which now contains possibly a value using the friend from the mask=3 update) with dp[2] + xi. That's fine: we are effectively allowing using the friend on top of previous combinations. However, could we double count? This update uses dp[2] old, not including the friend. So it's okay: it's exactly considering adding the friend to a subset that didn't include the friend. But careful: Could dp[3] already have a value that includes the friend? Then dp[2]+xi is using the friend once, so it's fine. However, there is risk: If we later, when we get to an even lower mask, update dp[2] using the friend? That's not relevant. The main issue: When we update dp[3] from mask=3, we are essentially considering adding the friend to a subset that may already contain the friend (since dp[3] old might already include the friend from previous friends). That's fine because we are allowed to add the friend again? No, we are not allowed to hire the same friend multiple times. But the DP state represents a set of problems solved, not which friends used. The recurrence dp[newmask] = min(dp[newmask], dp[mask] + xi) if we ensure that dp[mask] does not already include this friend? But dp[mask] can represent a combination that includes this friend from earlier? Wait, dp[mask] accumulates cost from previous friends only. When we add a new friend, we are updating based on dp[mask] from before this friend is considered. So if we update in place, we must ensure we use dp[mask] from the state before any updates with this friend. If we iterate masks from high to low, when we get to a mask, has dp[mask] been updated by this friend? It might have been updated if mask was a newmask from some higher mask. For example, suppose friend_mask=2 (10). Full=3. Start with mask=3: newmask=3|2=3 -> update dp[3] (maybe). Then mask=2: has dp[2] been updated? It hasn't because mask=2 is lower; we haven't processed it yet. So it's old. Then mask=1: old. Then mask=0: old. So dp[mask] for masks that are not updated as newmask before being processed will be old. However, could a mask be updated as newmask from a higher mask before we process it? For mask to be updated as newmask from a higher mask, that would mean there exists some mask' > mask such that mask' | friend_mask = mask. But mask'|friend_mask is at least mask' (since OR adds bits). So it can't be less than mask' unless friend_mask is zero. So newmask >= mask'. So if mask' > mask, then newmask >= mask' > mask, so it cannot equal mask. So a mask is never updated from a higher mask to a lower mask. Therefore, when iterating from high to low, any mask we process will not have been updated in this pass because any update to it would come from a lower mask (since newmask > mask). Since we process higher masks first, lower masks haven't been processed yet, but they could be updated by higher masks? As argued, higher mask cannot produce lower newmask. So no mask is updated before we process it. Therefore, dp[mask] remains old for all masks when we process them in descending order. That's good! Then we can safely do in-place update: for mask from full down to 0: dp[mask | friend_mask] = min(dp[mask | friend_mask], dp[mask] + xi). But we must be careful about the order of iteration: we are modifying dp[mask | friend_mask] which is either equal to mask (if friend_mask subset of mask) or larger. Since we are going from high to low, we might modify a state that we have already processed (if mask | friend_mask is less than current mask? Actually if mask | friend_mask is less than mask, that would require friend_mask to have bits not in mask and result in a number less than mask? Consider mask=4 (100), friend_mask=1 (001) => mask|friend=5 (101) >4. So it's greater. In general, OR can't reduce the integer value? Actually if bits are added, the integer value increases if the added bit corresponds to a higher position? Not necessarily: Example: mask=2 (10), friend_mask=1 (01) -> mask|friend=3 (11) which is greater. Another: mask=1 (01), friend_mask=2 (10) -> 3 >1. So OR yields a number that is at least the maximum of the two, but could it be less? Suppose mask=3 (11), friend_mask=0 -> unchanged. If friend_mask has bits only within mask, OR = mask, so it's equal. So newmask is either equal to mask or greater. So when iterating from high to low, if newmask > mask, then newmask is a higher number than mask. Since we are going downward, we have already processed newmask earlier! That means we would be updating a state that has already been processed in this pass. Is that allowed? In knapsack with addition (weight), we iterate from high to low to avoid using the same item multiple times because we update dp[w] from dp[w-weight] (which is lower index) and by the time we get to w, dp[w-weight] hasn't been updated. Here, we are updating a higher index from a lower index. If we go high to low, we update higher indices (which we have already processed) from lower indices (which we haven't processed yet). That's okay as long as we don't later use those updated higher indices in the same pass for further updates from even lower indices? But we won't, because we have already processed higher indices and won't revisit them (since we're descending). So updating them after processing is fine; it won't affect the rest of the pass because those higher indices won't be used again. But does it cause double counting? Let's check: Suppose we have mask=0 (lowest). We'll process mask=0 at the end. When we process mask=0, we will update newmask = friend_mask. That newmask is >0, and we have already processed all masks >0 earlier. So we update dp[friend_mask] after it's been processed. That's okay because we are just setting a value for that mask, but we might miss the opportunity to combine this friend with other friends that we might have already considered when processing that mask? Wait, we need to allow the possibility of using this friend together with other friends that have been already added in previous steps. Our DP state dp[mask] is the minimal cost using all friends processed so far. When we add a new friend, we want to compute new dp that includes this friend. The correct update is: new_dp[newmask] = min(old_dp[newmask], old_dp[mask] + xi) for all mask. One way is to copy old_dp to new_dp, then for each mask, new_dp[mask|f] = min(new_dp[mask|f], old_dp[mask] + xi). But if we do in-place descending, we need to ensure we use old_dp[mask] (the value before any updates with this friend) to update. Since we iterate descending, when we get to mask, old_dp[mask] hasn't been updated because any update to mask would come from a higher mask (since newmask >= mask). As argued, higher mask can't update mask because newmask >= higher mask > mask. So mask remains old. However, when we update dp[mask|f], we are writing to a location that may have already been processed. That's okay because we are effectively computing new_dp for that mask|f. However, later when we process a lower mask, we might need to use dp[mask|f] as a base for further updates? No, because we only use dp[mask] (the lower mask) for updates; we don't use dp[mask|f] as a source for other updates in the same pass (since we iterate over masks, not over newmask). So it's fine to update a state that we have already passed. The only potential problem: Suppose we have mask1 and mask2, both produce same newmask. If we process mask1 first (higher mask) and update dp[newmask], then when we process mask2 later (lower mask), we will again update dp[newmask] using old_dp[mask2]. That's okay because we are comparing with the (possibly updated) dp[newmask] which may now contain the value from mask1. That's exactly what we want: we want the min of old_dp[newmask] and (old_dp[mask1]+xi) and (old_dp[mask2]+xi). However, note that after mask1 update, dp[newmask] might be changed, but when we process mask2, we still use old_dp[mask2] (which is correct). So final dp[newmask] will be min(old_dp[newmask], old_dp[mask1]+xi, old_dp[mask2]+xi). Good. Also, if dp[newmask] was updated from mask1 and we later, when processing mask2, use dp[newmask] as a base for another update? No, we don't. So no double counting.
But what about the possibility of using the same friend twice? Could that happen? Suppose we have mask = friend_mask. Then dp[friend_mask] after processing mask=0 might be set to xi (if old_dp[0]=0). Later, when we process mask = friend_mask (which we will, because we iterate descending), we might consider dp[friend_mask] + xi to update dp[friend_mask | f] = dp[friend_mask] (since friend_mask | f = friend_mask if f subset of friend_mask). That would be adding the same friend again, costing 2*xi. But is that allowed? In our DP semantics, we should not allow using same friend multiple times. However, does the update from mask = friend_mask use old_dp[friend_mask] or new dp? At the time we process mask = friend_mask, dp[friend_mask] might have been updated from mask=0 earlier. Since we are iterating descending, mask = friend_mask will be processed after mask=0? Depends on numeric values. friend_mask could be, say, 2. Then descending order: full, ..., 3, 2, 1, 0. So we process mask=2 after mask=3, but before mask=1 and 0. At that point, dp[2] has been updated from mask=0? But mask=0 is processed after mask=2 because descending goes to 0 last. So when processing mask=2, we haven't processed mask=0 yet. So dp[2] is still old_dp[2] (i.e., before adding this friend). That's good. So the update from mask=0 to dp[2] happens later, after we have processed mask=2. So when we process mask=2, dp[2] is old. Thus we won't use the friend twice in the same pass. Good. So descending order works.
What about when friend_mask is such that some mask | f = mask (i.e., f subset of mask)? Then newmask = mask. When processing mask, we would update dp[mask] = min(dp[mask], dp[mask] + xi). That's wasteful but doesn't cause multiple counting because dp[mask] hasn't been updated from this friend yet. It just compares dp[mask] with itself+xi, which doesn't change. So fine.
Thus we can perform in-place DP for each friend with a loop over mask from (1<<m)-1 down to 0. That is O(2^m) per friend. Good.
Now, after we process all friends with same ki, we compute candidate. But note: The DP we maintain includes all friends processed so far (i.e., with ki <= current threshold). So after processing all friends up to a certain ki, we have the optimal cost using any subset of those friends. Then candidate = ki * b + dp[full]. However, careful: The monitors cost is b per monitor, and we are using M = ki. But what if the optimal subset among friends with ki <= current ki has max ki less than current ki? Then we could actually buy monitors = max_ki_used < ki, and total cost would be lower than kib + dp[full] because monitors cost would be less. But we are evaluating at ki, which is the threshold we are processing. However, the dp[full] value at this threshold might represent a subset whose max ki is less than ki, but we are forced to pay kib if we set M = ki. But we don't have to set M = ki; we could set M = the actual max ki used. That would be cheaper. But is that combination captured by some earlier threshold? Yes, if the subset uses max ki = K0 (some friend with ki = K0), then when we processed the threshold equal to K0 (after adding all friends with ki <= K0), dp[full] at that threshold would have been at most the cost of that subset (since all friends with ki <= K0 are available). And candidate = K0b + dp[full] would be exactly the total cost for that subset. So the optimal total will be found at the threshold equal to the max ki of the optimal subset. So we should not compute candidate for threshold ki using dp[full] if the best subset uses max ki < ki because that candidate would be higher than the one at the actual max ki (if we had computed it). But we are evaluating candidate for each ki, and the answer is min across all candidates. So if dp[full] at ki uses a subset whose max ki is lower, candidate = kib + dp[full] may be larger than the candidate at lower ki (since lower ki * b + maybe same dp[full]? But note dp[full] might be same or lower at lower ki? Actually as ki increases, dp[full] can only decrease or stay same because we have more friends available. So at ki, dp[full] <= dp[full] at any lower ki. So candidate at ki could be lower than candidate at lower ki if the reduction in dp[full] outweighs increase in monitors cost. That's possible. However, if the optimal subset uses max ki less than ki, then at ki, dp[full] might be the same as at that lower ki (if no better combination is found). Then candidate at ki would be higher due to higher monitors cost. So the min across all ki will still be attained at the lower ki where monitors cost is lower. So it's fine to compute candidate at every distinct ki; the true optimum will be among them.
But careful: Suppose the optimal subset uses friends with max ki = K0, and also there exists a friend with ki = K1 > K0 that is not used but allowed; however, maybe at K1, we find a better dp[full] (lower sum xi) that uses some friends with ki = K1, and the total K1b + that sum might be lower than K0b + cost_opt. That's possible. Then the optimal total might be at a higher ki. That's fine, it will be captured at that higher ki. So overall min across thresholds yields correct answer.
Now, implementation details: Since n is only 100, we can just store friends and sort by ki. Then initialize dp array of size 1<<m with INF, dp[0]=0. Also we need a variable answer = INF.
We will iterate through friends in sorted order. But we need to group by ki. So we can process friends one by one, update dp. After each friend (or after finishing a group with same ki), we can compute candidate using current ki (the ki of the just processed friend). However, careful: If there are multiple friends with same ki, we should only compute candidate after we have added all of them, because otherwise we might miss combinations that require multiple friends with that ki. So we can, as we loop, keep track of last_ki. When we encounter a friend with a different ki, we compute candidate for last_ki using dp before adding this friend? Actually we want to compute after processing all friends with that ki. So we can do: sort friends by ki. Initialize last_ki = -1. For each friend in sorted order:
if friend.ki != last_ki:
if last_ki != -1: compute candidate for last_ki (using current dp, which includes all friends with ki <= last_ki).
update last_ki = friend.ki
then process this friend: update dp with friend.
After loop ends, compute candidate for the last_ki (since after processing last group, dp includes all friends). Then answer = min(candidate, answer). Also, we might consider if it's possible to have answer from M=0? But ki >=1, so not necessary. Also if dp[full] remains INF, answer stays INF -> output -1.
Edge Cases:
Multiple friends with same ki: group correctly.
Large b and ki, so answer may be large (exceed 2^63?) Up to 1e9 * 1e9 + n*1e9 = 1e18+1e11 ~ 1e18, fits in 64-bit.
There is possibility that we could buy monitors but not hire any friend? Not solve problems. So ignore.
Now test with examples.
We'll implement DP update loop as:
for mask in range(full, -1, -1):
newmask = mask | friend_mask
if dp[mask] + xi < dp[newmask]:
dp[newmask] = dp[mask] + xi
But need to ensure dp[mask] is not INF. So check if dp[mask] != INF.
Potential optimization: Since m <=20, full up to ~1e6, loops fine.
Now, what about the possibility of integer overflow in dp[mask] + xi? Use large INF like 10**19.
Now, we must also consider that the monitors cost b is per monitor and we need to buy integer number of monitors. But we are using M = ki, which is integer. So fine.
One more nuance: Could it be optimal to buy zero monitors? Since ki >=1, we would need at least 1 monitor to hire any friend. But perhaps there are no problems? m>=1, so need at least one friend, thus monitors needed. So M=0 not feasible.
Thus algorithm is straightforward.
Now, we must produce output as minimal amount or -1.
Now let's test with custom cases.
Case: n=1, m=1, b=5, friend: x=10, ki=3, mi=1, problem1. Then after processing friend, dp[full]=10 at ki=3. candidate=3*5+10=25. Answer 25.
Could there be a better solution? No.
Case: n=2, m=2, b=10. Friend1: x=100, ki=1, solves p1; Friend2: x=1, ki=100, solves p2. Sorted: k1=1, k2=100. Process friend1: dp[01]=100. full=11. candidate at k=1: dp[11]=inf -> ignore. Process friend2: update dp: from mask=01? Actually after friend1: dp[01]=100, dp[00]=0, dp[10]=inf. After friend2: from mask=00 -> newmask 10 => dp[10]=1; from mask=01 -> newmask 11 => dp[11]=101; from mask=10? dp[10] is inf before update? Actually we process descending: full=3,2,1,0. We'll compute accordingly. After update, dp[11]=101. candidate at k=100: total=10010+101=1101. But maybe we could instead use both friends: total=10010? Wait, if we set M=100, total monitors cost 1000, plus 101 =1101. If we instead set M=1, we could only use friend1, can't cover p2, so impossible. So answer 1101. But maybe we could also consider M=100? That's the only. So answer is 1101. But maybe we could also consider not using friend2 and only friend1? Not full. So fine.
Now consider if b is small: maybe better to buy more monitors to get cheaper xi sum. This algorithm will catch that.
Now, complexity: sorting O(n log n). DP per friend O(2^m). For n=100, m=20, about 100 * 1,048,576 = 104,857,600 operations. In Python, that might be ~2-3 seconds in PyPy? Possibly okay if optimized. But we need to be careful with loops in Python. We can try to speed up by using list of ints and for loop with local variables. Also, we can precompute newmask for each mask? That would be O(2^m) per friend as well, but we still need to compute mask|friend_mask, which is fast. We can also try to reduce number of updates by only iterating over masks where dp[mask] is not INF, but that could be many anyway. We'll implement straightforwardly.
Alternative approach: Since m small, we can also do DP over subsets while iterating over friends, but we can also use bitset dynamic programming like DP[mask] = min cost to cover mask, and update by taking min with dp[mask_without_f] + xi? But friend solves multiple problems, not a single. So OR update needed.
We'll implement in Python using PyPy.
But note: In Codeforces problem 99C? Actually I think it's Codeforces Round #... But typical time limit 2 seconds. However, many Python solutions for DP over subsets with n up to 100 and m=20 might pass if optimized. Let's think: 100 * 2^20 = 100M iterations. Each iteration does a few operations: check if dp[mask] is INF (maybe compare), compute newmask, compare and assign. In Python, 100M might be borderline but maybe okay in PyPy with optimizations (using built-in functions? Could use array module, but still loop). We could reduce the constant by using for mask in range(full, -1, -1): but Python's range with step -1 is okay. But maybe we can iterate over all masks and use a for loop with a local variable for dp array and friend_mask and xi.
But maybe there is a better approach: Since n=100, we could also consider iterating over subsets of friends? Not, 2^100 impossible.
Maybe we can use meet-in-the-middle? Not needed.
Thus we'll proceed with Python DP.
However, note that n=100 and m=20, but DP update per friend is O(2^m) which is okay.
But we also need to consider memory: dp array of size 2^20 ~ 1M, each as a Python int, memory ~ 8MB, okay.
Now, implementation steps:
Read n, m, b.
Initialize friends list.
For i in range(n):
read line with xi, ki, mi
then read next line with mi integers (problems)
construct mask: for each p, mask |= 1 << (p-1)
append (ki, xi, mask) maybe. Note: we need to sort by ki, so store as tuple (ki, xi, mask)
Sort friends by ki (if ki same, any order is fine).
full = (1 << m) - 1
INF = 10**19 (or 1<<60 something)
dp = [INF] * (full+1)
dp[0] = 0
ans = INF
last_ki = -1
for each (k, x, mask) in friends:
if k != last_ki:
if last_ki != -1:
# compute candidate for last_ki
if dp[full] < INF:
total = last_ki * b + dp[full]
if total < ans: ans = total
last_ki = k
# process this friend: update dp in descending order
for mask2 in range(full, -1, -1):
if dp[mask2] != INF:
newmask = mask2 | mask
cost = dp[mask2] + x
if cost < dp[newmask]:
dp[newmask] = cost
after loop, process last group
if last_ki != -1 and dp[full] < INF:
total = last_ki * b + dp[full]
if total < ans: ans = total
if ans >= INF: print(-1)
else: print(ans)
But we need to be careful: When we compute candidate after processing a group, we must ensure dp[full] is the minimal cost using friends up to that ki (including that group). That's correct.
Now, test with example1:
friends sorted: (1,100, mask=2), (2,100, mask=1). Process first: k changes from -1 to 1, last_ki=1, then process friend1: update dp. After processing, we don't compute candidate because we only compute when k changes next time. So after friend1, we haven't computed candidate for k=1. That's correct because we haven't added all friends with k=1? Actually there might be multiple friends with k=1, but here only one. However, we should compute candidate for k=1 after processing all friends with k=1, before moving to k=2. Our code currently computes candidate when encountering a new k, before updating with the new friend. That means after processing all friends with k=1, we will compute candidate at the moment we encounter friend with k=2 (i.e., when k != last_ki). At that point, last_ki is still 1, and dp reflects inclusion of all friends with ki <=1 (since we haven't added friend with k=2 yet). So we compute candidate for k=1. Then update last_ki=2 and process friend2. After loop ends, we compute candidate for last_ki=2. That yields correct.
Now if there are multiple friends with same ki, they will all be processed sequentially without computing candidate in between, because only when k changes do we compute. After the last friend of that group, when we encounter next friend with different ki (or end), we compute candidate. Good.
Now what if the smallest ki is >0 but there is no friend that can solve some problem? Then dp[full] never becomes finite, ans stays INF, output -1.
Now, we must consider the possibility of using no monitors but friends with ki=0? But constraints say 1 ≤ ki, so not possible. So ignore.
Now, is there any case where we need to consider buying monitors but not using any friend with that ki? Actually we may buy monitors M that is not equal to any friend's ki but is larger than the max ki used. That would be suboptimal, as argued. So not needed.
But what if b is 0? Then monitors cost nothing. In that case, we can buy any number of monitors for free, so effectively we can ignore monitors and we just need min sum xi covering all problems. But our algorithm still works: because b=0, monitors cost is zero regardless of M. However, we need to be careful: The optimal M can be any number, but we only evaluate at distinct ki. Could the optimum be achieved with M less than min ki? If b=0, we can set M = 0 and still hire friends? No, because we still need at least ki monitors to hire friend, so if M=0, cannot hire any friend (since ki>=1). So we need at least the max ki among hired friends. So M must be at least that max. Since b=0, any M >= max_ki yields same monitor cost (0). So we could set M = max_ki. So evaluating at M = max_ki (which is one of the ki values) gives the same total cost. So algorithm still yields correct min sum xi because monitor cost is 0. So fine.
Now, what if b is negative? Not allowed (b >= 1).
Now, we must consider that dp values can be large, but INF should be larger than any possible total. Let's set INF = 10**19.
Now, potential pitfalls: Sorting friends by ki, but we might have many friends with same ki, and DP update order among them doesn't matter (since we treat each friend as an item). However, the DP update for each friend uses descending loop. That ensures each friend used at most once. Good.
Now, we also need to think about integer overflow in multiplication: last_ki * b. last_ki up to 1e9, b up to 1e9, product up to 1e18, within Python's arbitrary precision, fine.
Now, let's test more cases.
Case: n=2, m=3, b=10.
Friend1: ki=5, x=50, solves p1,p2 -> mask=110? Actually bits: p1=1<<0=1, p2=2 => 3.
Friend2: ki=10, x=1, solves p3 -> mask=4.
Sorted: k=5 then 10.
After friend1: dp[3]=50. full=7.
At k=5, dp[7] inf, candidate ignore.
After friend2: update: from mask=3 -> newmask=7 cost=51; from mask=0 -> mask=4 cost=1. So dp[7]=51. candidate at k=10: total=10*10+51=151. But could we instead set M=5 and use both friends? Friend2 requires ki=10, cannot be hired if M=5. So impossible. So answer 151. However, maybe we could use only friend1? Not full. So correct.
But consider if b is small, like b=1. Then M=10 monitor cost 10, plus 51 =61. M=5 cost 5+? Cannot hire friend2, so impossible to cover p3. So only M=10 works.
Now, what if there is a friend with ki=5 that solves all problems? Then we would have dp[7]=? e.g., friend3: ki=5, x=30, mask=7. Sorted: ki=5 friends include friend1 and friend3. After processing all ki=5 friends, dp[7] might be 30. Then candidate at k=5: total=5*1+30=35. Then later at k=10, dp[7] might still be 30 (since no better) total=10+30=40 >35, so min is 35. So answer 35.
Now, need to ensure we compute candidate for k=5 after processing all ki=5 friends, before adding any ki=10 friends. That's done by computing when k changes to 10. Good.
Now, consider scenario where the optimal subset uses only friends with ki less than some threshold, but there is another friend with higher ki that is not used. The candidate at the higher threshold might be larger, but we still have candidate at the lower threshold. So min will pick lower.
Now, consider scenario where there are multiple distinct ki and the DP improvement occurs exactly at the highest ki among friends. That's captured.
Now, let's think about correctness of DP update order: descending over mask ensures each friend considered only once. Let's test with a small example to confirm no double use.
Suppose we have dp initially: dp[0]=0.
Friend: mask=1, x=10.
We iterate mask from full (say 3) down to 0:
mask=3: dp[3]=INF -> skip (or check, if INF, skip).
mask=2: dp[2]=INF skip.
mask=1: dp[1]=INF skip.
mask=0: dp[0]=0, newmask=1, set dp[1]=10.
Now after loop, dp[1]=10. Friend used once.
Now suppose we have two friends: first friend (mask=1, x=10) processed, dp[1]=10. Then second friend (mask=2, x=20). Process in descending:
mask=3: dp[3]=INF, newmask=3|2=3 => if dp[3] > dp[3]+20? INF, skip? Actually dp[3] INF, so no update.
mask=2: dp[2]=INF? Actually after first friend, dp[2] is INF. So skip.
mask=1: dp[1]=10, newmask=1|2=3, set dp[3]=30.
mask=0: dp[0]=0, newmask=2, set dp[2]=20.
Now dp[2]=20, dp[3]=30. No double counting.
Now consider if we processed the second friend with ascending order: mask from 0 to full:
mask=0: set dp[2]=20.
mask=1: dp[1]=10 (old), set dp[3]=30.
mask=2: dp[2] now is 20 (updated), newmask=2|2=2, set dp[2]=min(20,20+20)=20, ok.
mask=3: dp[3]=30, newmask=3|2=3, maybe set dp[3]=min(30,30+20)=30, ok.
But in this case, we didn't double count either because the second friend was only considered once? Actually we used dp[2] which was just updated from mask=0, but that's okay because we are still only adding the second friend once: from mask=2, we are trying to add friend to a subset that already includes the second friend? Wait, mask=2 after update corresponds to a subset that includes only the second friend (since we set dp[2] from mask=0). Then using mask=2 to add the same friend again would produce mask=2 again (since OR with its own mask), and we would consider dp[2] + x = 20+20=40, which doesn't improve dp[2] (20). So no harm. However, could it lead to using the same friend twice in a chain? For instance, if friend_mask=1, and we have dp[0]=0, dp[1] set from mask=0. Then when we later process mask=1 (now updated), we would update newmask=1|1=1 with cost dp[1]+10 = 10+10=20, which would set dp[1]=20? That would be using the same friend twice, which is not allowed. But would that happen? Let's simulate ascending: friend_mask=1, x=10.
mask=0: set dp[1]=10.
mask=1: dp[1] is now 10, newmask=1|1=1, cost 20, if we update, we would set dp[1]=20, which is double usage. So ascending order would incorrectly allow using the same friend multiple times. Indeed, because when we get to mask=1, dp[1] has already been updated using this friend, and we are considering adding the same friend again. So we must avoid that. Descending order avoids this because we process higher masks first, and the mask where we would have updated (mask=0) is processed after mask=1, so dp[1] is still old when we process mask=1. So no double addition. Good.
Thus descending order is crucial.
Now, the DP update only needs to consider masks where dp[mask] is not INF, but we still need to iterate all masks. We could only iterate over masks that are currently reachable, but that would require maintaining a list of masks, which could be up to 2^m anyway. So not needed.
Now, we can think about potential optimization: Because n is up to 100, but m=20, the DP per friend can be heavy but okay.
Now, let's consider edge: If m=20, full=1048575. Loop for each friend 100 times -> 100 million iterations. Each iteration does: if dp[mask] != INF: compute newmask and update. In worst case, after some friends, many dp entries become finite. So we will do the check for all masks regardless. That's okay.
Now, to improve speed, we can use Python's local variables inside loop:
dp_local = dp
fm = mask_friend
cost_x = x
for msk in range(full, -1, -1):
cur = dp_local[msk]
if cur != INF:
nm = msk | fm
newcost = cur + cost_x
if newcost < dp_local[nm]:
dp_local[nm] = newcost
This should be relatively fast.
Now, we should use sys.stdin.read to read all input fast.
Implementation steps:
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
b = int(next(it))
friends = []
for _ in range(n):
xi = int(next(it)); ki = int(next(it)); mi = int(next(it))
mask = 0
for __ in range(mi):
p = int(next(it))
mask |= 1 << (p-1)
friends.append((ki, xi, mask))
friends.sort() # sort by ki, then xi, etc.
full = (1 << m) - 1
INF = 10**19
dp = [INF] * (full + 1)
dp[0] = 0
ans = INF
last_ki = -1
for k, x, mask in friends:
if k != last_ki:
if last_ki != -1:
if dp[full] < INF:
total = last_ki * b + dp[full]
if total < ans:
ans = total
last_ki = k
# update dp
# descending loop
for msk in range(full, -1, -1):
cur = dp[msk]
if cur != INF:
nm = msk | mask
newcost = cur + x
if newcost < dp[nm]:
dp[nm] = newcost
# after all friends
if last_ki != -1 and dp[full] < INF:
total = last_ki * b + dp[full]
if total < ans:
ans = total
if ans >= INF:
print(-1)
else:
print(ans)
if name == "main":
main()
Now, test with given examples.
Example1:
n=2,m=2,b=1, friends: (1,100,mask=2), (2,100,mask=1). Sorted: (1,100,2), (2,100,1). Process first: last_ki changes to 1, update dp: from msk=3->0: update: msk=0 sets dp[2]=100. After loop, last_ki still 1. Next friend: k=2 != last_ki (1), so compute candidate for last_ki=1: dp[full]=dp[3] is INF? Actually after first friend, dp[3] still INF, so no candidate. Then set last_ki=2, update dp with friend2: updates: from msk=3 down: msk=3 INF; msk=2: dp[2]=100 -> nm=2|1=3, set dp[3]=200; msk=1: INF; msk=0: set dp[1]=100. After loop, end of friends. Then after loop, compute candidate for last_ki=2: dp[full]=200, total=2*1+200=202, ans=202. Output 202. Good.
Example2:
n=3,m=2,b=5
friends: (1,100, mask1=1), (1,100, mask2=2), (1,200, mask3=3)
Sorted (all ki=1). Process first: last_ki changes to 1, update dp: after first friend dp[1]=100. Next friend: k=1 == last_ki, so no candidate; update dp: using mask=2: from msk=2? Actually dp currently: dp[0]=0, dp[1]=100. Update: msk=3->0: msk=2? Let's just trust algorithm. After second friend: dp[2]=100, dp[3]=200. Next friend: k=1 == last_ki, update dp with mask=3: from msk=3 down: msk=3: cur=200, nm=3|3=3, newcost=400 >200; msk=2: cur=100, nm=2|3=3, newcost=300 >200; msk=1: cur=100, nm=1|3=3, newcost=300 >200; msk=0: cur=0, nm=3, newcost=200 (200), dp[3] stays 200. So dp[3]=200. End of friends. After loop, compute candidate for last_ki=1: dp[full]=200, total=1*5+200=205, ans=205. Output 205. Good.
Example3:
n=1,m=2,b=1, friend: (1,1,mask=1). Process: last_ki=1, update dp: dp[1]=1. After loop, compute candidate for last_ki=1: dp[full]=dp[3] INF, ans remains INF, output -1. Good.
Now, we must consider if there is any scenario where dp[full] becomes finite only after processing some friends, but the candidate for that ki has already been computed before those friends? That cannot happen because we compute candidate only when we encounter a new ki or at the end. If all friends have same ki, we compute candidate only after processing all of them (at the end). Good.
Now, what if there are friends with ki = 0? Constraint says ki >= 1, so ignore.
Now, large numbers: Use INF = 10**19, which is > (b * max_ki + sum xi) max around 1e91e9 + 1001e9 = 1e18 + 1e11, so 1e19 is safe.
Now, performance: 100 * 1,048,576 loops with a few operations. In Python, each iteration may take around 50 ns? Actually Python is slower, maybe 100 ns per simple operation? 100M * 100 ns = 10 seconds. That's too slow. Let's estimate: On PyPy, loops can be faster. For reference, typical Python can do about 50 million simple operations per second? Actually CPython can do maybe 50 million integer operations per second? Not really; CPython is slower: a simple loop with a few operations might run at ~30-50 million per second? Let's benchmark mental: for i in range(10000000): pass takes about 0.3 seconds? Actually CPython: 10 million empty loop takes about 0.5-0.8 seconds? But with operations, slower. 100 million may take 5-10 seconds. PyPy often faster for loops, maybe 2-3 seconds for 100 million simple operations. Might be okay with optimizations. However, we can attempt to reduce the constant by skipping INF checks? But we need to check because dp[mask] may be INF for many masks early on. But eventually many become finite. However, we could speed up by using a list of current masks to iterate over, but that may add overhead. Another approach: Since m=20, we could use bit DP with "for mask in range(full+1):" but then we need to avoid double counting. But we could also use DP with superset enumeration? Not needed.
Alternative: Since n is only 100, we could also consider a different DP: For each subset mask, we compute min cost to achieve it, but we can process friends in any order. The DP we have is standard.
We might also note that we can treat the monitors as part of a cost function: total = M*b + cost(mask), where M must be >= max ki of used friends. We can think of each friend as having effective cost = xi, but also imposes a requirement on M. This is similar to "minimum cost to cover set with items each having a weight and a requirement". A known approach is to sort by ki and then DP, which is exactly what we do.
So the algorithm is correct.
Now, can we reduce the number of DP updates? Since we only need dp[full] at the end of each group, maybe we can prune: But not necessary.
Nevertheless, we can attempt to micro-optimize:
Use local variables for dp, full, INF inside loop.
Use for mask in range(full, -1, -1): but range in Python 3 creates a range object and iterates, that's fine.
Use bitwise OR: newmask = mask | fm.
Use if dp[mask] + x < dp[newmask] then assign.
Use a variable cur = dp[mask]; if cur != INF: then compute.
Might use memoryview? Not needed.
Alternatively, we could use array('Q') from array module for dp, but Python list is fine.
We could also consider using PyPy's JIT which may optimize loops.
Now, note that b can be up to 1e9, and ki up to 1e9, product up to 1e18, fits in Python int.
Now, edge case: If there are friends with same ki, we compute candidate only after the group. But what if the optimal subset uses only a subset of friends from that group, and we could also consider a smaller M equal to the max ki among them? But that's exactly the ki value. However, what if the optimal subset's max ki is exactly that ki, but we might achieve a lower total by using some friends from that group but not all? The DP will compute the minimal cost for that group, so fine.
Now, there is a nuance: Could the optimal M be less than the ki of any friend? Only if we don't hire any friends, but that's impossible. So fine.
Thus answer is ready.
Now, check with some random tests.
We'll write a small brute force for small n, m to verify.
But for analysis, I'll manually think of a tricky case: Suppose there are two friends:
Friend A: ki=5, x=10, solves all problems (mask full).
Friend B: ki=1, x=100, solves all problems.
b=1.
Sorted: B (ki=1), A (ki=5).
After processing B: dp[full]=100, candidate for ki=1: total=1+100=101.
After processing A: dp[full] becomes min(100, 10) =10? Actually update with A: from mask=0 gives dp[full]=10; from other masks may give same. So dp[full]=10. Then candidate for ki=5: total=5+10=15. So answer 15, which is better than 101. So optimal uses friend A with higher ki but cheaper cost.
Now, if b=100, then ki=1 candidate: 1100+100=200, ki=5 candidate:5100+10=510, min=200. So optimal uses friend B with lower ki despite higher xi.
Now, if b=20, ki=1: 20+100=120, ki=5: 100+10=110? Actually 5*20=100 +10=110, so min 110. So good.
Now, ensure that DP update for friend A after friend B doesn't inadvertently increase dp[full] (it shouldn't). Our DP yields min.
Now, consider if there are overlapping subsets: fine.
Now, what about multiple friends with same ki and same problems? DP will take min cost.
Now, one more nuance: The monitors cost b is per monitor, and we are buying integer monitors. Could we buy fractional? No.
Now, what about the possibility that we need to buy monitors, but maybe we don't need to buy exactly the max ki; we could buy less if we use only friends with lower ki? Already considered.
Now, let's test the algorithm with a case where there are many friends and large m.
But we are confident.
Now, I'll also consider if there is any trick: The friend requires that Gena's computer is connected to at least ki monitors. That means if Gena buys M monitors, he can hire friend i if M >= ki. So it's exactly as modeled.
Now, verify that we don't need to consider buying monitors after hiring friends? Order doesn't matter, we just need M such that for all hired friends, M >= ki.
Now, final answer.
Potential improvements: Since b up to 1e9, last_ki * b could be large, but okay.
Now, I'll produce final solution.
But before finalizing, I should check the possibility of overflow in dp[mask] + xi: dp[mask] up to INF (1e19), but we only add xi (1e9) when dp[mask] not INF, so safe.
Now, I think solution is correct.
Now, produce final answer.
One more thought: The problem statement says: "the i-th friend asks Gena xi rubles for his help in solving all the problems he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least ki monitors, each monitor costs b rubles." So monitors cost b each. It's not said that Gena must buy monitors before hiring, but it's implied he can buy any number, cost b each. So total cost includes monitors.
Our model: total = M*b + sum xi. And M must be at least max ki. That's correct.
Now, the input format: "The following 2n lines describe the friends. Lines number 2i and (2i + 1) contain the information about the i-th friend." So there are 2n lines after first line. We read accordingly.
Now, maybe we need to be careful: In the input example 2, they wrote:
3 2 5
100 1 1
1
100 1 1
2
200 1 2
1 2
We parsed correctly.
Now, think about corner: n=0? n >=1 per constraints (1 ≤ n). So okay.
Now, I think we are ready.
But let's test a case where multiple friends with same ki and overlapping problems can be combined to achieve full coverage at lower cost? DP will find min.
Now, we might want to handle large INF: Use INF = (1 << 60) or something: 1<<60 = about 1.15e18, which may be borderline if total can be up to 1e18? Actually max possible: b=1e9, max ki=1e9 => 1e18; plus sum xi max = 100*1e9 = 1e11, total <= 1.0001e18 < 1.15e18. So 1<<60 = 1152921504606846976 ≈ 1.1529e18, which is > 1e18. So we can use that. Or use 10**19.
Now, code.
Now, I'll also consider if there is any need to use "long long" in Python it's automatic.
Now, final answer.
But wait: The algorithm as described has a subtle bug: When we compute candidate for last_ki after encountering a new ki, we use dp[full] that currently includes all friends processed so far, which are those with ki <= last_ki (since we haven't added the new friend with higher ki). That's correct. However, after processing all friends, we compute candidate for the last group. This works.
But what about the case where after processing all friends, the dp[full] may be finite, but we might have already computed candidate for the last_ki at the point we encountered the last friend? Actually the last group: after processing the last friend (which belongs to some ki), we haven't computed candidate for that ki because we only compute when encountering a new ki. At the end of loop, we compute it. That's fine.
Now, what about the case where there is only one distinct ki? Then we compute candidate only at the end, after all friends processed. That's correct.
Now, let's test with only one friend that covers all problems: n=1,m=1,b=5, friend: x=10,ki=3, mask=1. After processing friend, dp[full]=10. At end, last_ki=3, candidate = 3*5+10=25. ans=25. Output 25.
Now, what about scenario where there are friends with ki=1 and ki=2, but the optimal subset uses only ki=1 friends, but we computed candidate for ki=1 after processing all ki=1 friends (before processing ki=2). That candidate is correct. After processing ki=2 friends, we compute candidate for ki=2, which may be higher. So min will be ki=1 candidate.
Thus correct.
Now, we must also consider that if there are friends with same ki, but we also could have multiple groups with same ki? Sorting groups them.
Now, one more nuance: The DP update uses descending loop from full to 0. This is O(2^m). However, we might be able to speed up by using "for mask in range(full, -1, -1)" but this includes all masks. That's okay.
Now, I will think if we can further optimize by using bit DP with "for mask in range(full+1)" but need to avoid double counting. We could also use a temporary dp2 array where we copy dp and then for each mask, update dp2[mask|f] = min(dp2[mask|f], dp[mask] + x), then assign dp = dp2. That would also be O(2^m) but with extra memory and copying. Copying 1M ints 100 times is 100M copies, each copy might be similar cost to loops. But in Python, copying a list of 1M might be faster than iterating? Not sure. Usually iterating and copying are both O(2^m). But we also need to compute updates. The in-place descending loop seems efficient.
Now, I'll produce final solution.
One more thing: In the DP update, we do if cur != INF: compute newcost. This is a branch. Many dp entries may be INF initially, but after some friends, many become finite. So the branch may be taken many times. Could we accelerate by using "for mask in reachable_masks" list? But that list could become large (up to 2^m). So not beneficial.
Perhaps we can do bit DP by iterating over all subsets and updating supersets? But that would be more expensive.
Thus we proceed.
Now, I will present the solution.
Now, final answer: code as described.
But before finishing, test with a random small case and brute force to be absolutely sure.
Let's generate a small n=4, m=3, b random. Use brute force: iterate over all subsets of friends (2^4=16). For each subset, compute max_ki (if subset nonempty, else skip), check if union of problems covers all m. Then total = max_ki * b + sum xi. Take min. Compare with our algorithm.
Sorted: (1,10, mask=2), (2,4, mask=3), (3,5, mask=1)
Process friend1 (ki=1): dp[2]=10. candidate for ki=1: dp[3] inf -> none.
Process friend2 (ki=2): before processing, last_ki changes to 2, compute candidate for ki=1: dp[3] inf? Actually after friend1, dp[3] inf, so none. Then update with friend2: from dp[2]=10 -> newmask=2|3=3, dp[3]=14; from dp[0]=0 -> dp[3]=4; so dp[3]=4. So after friend2, dp[3]=4. Then candidate for ki=2? Not yet, because we haven't processed friend3, but last_ki is now 2. Next friend3: ki=3 != 2, so compute candidate for last_ki=2: dp[full]=4, total=22+4=8. ans=8. Then set last_ki=3, update with friend3: from dp[0]=0 -> dp[1]=5; from dp[1]? Actually dp[1] currently? after friend2, dp[1] maybe INF? Let's compute: after friend2, dp[1] might still be INF because no mask=1. So after friend3, dp[1]=5. Then update newmask: from dp[1]=5 -> newmask=1|1=1? No change; from dp[2]=10 -> newmask=2|1=3 -> dp[3] = min(4,10+5=15) stays 4; from dp[3]=4 -> newmask=3|1=3 stays 4. So dp[3] remains 4. After loop, compute candidate for last_ki=3: total=32+4=10. ans = min(8,10)=8.
Now brute force:
Subsets:
{} invalid.
{1}: max_ki=3, sum x=5, covers only {1} not full -> invalid.
{2}: max_ki=1, sum x=10, covers only {2} invalid.
{3}: max_ki=2, sum x=4, covers both -> total=22+4=8.
{1,2}: max_ki=max(3,1)=3, sum=15, covers both -> total=32+15=21.
{1,3}: max_ki=3, sum=9, covers both -> total=32+9=15.
{2,3}: max_ki=2, sum=14, covers both -> total=22+14=18.
{1,2,3}: max_ki=3, sum=19, total=25.
Min = 8. matches our answer.
Now, test with a case where the optimal subset uses a friend with ki=3 even though there is a subset with max_ki=2 but higher xi. We already did.
Now, test with a case where there are multiple groups and dp[full] becomes finite at a later group, but earlier group also gave finite but higher cost.
Seems correct.
Now, confirm that we didn't miss scenario where we could achieve full coverage with friends that have ki <= some value, but we might consider buying M less than that value? Actually if we have friends with ki <= M, we can hire them. So if we have a subset with max_ki = K, we can set M=K and hire them. If we set M smaller than K, we cannot hire the friend with ki=K. So that subset wouldn't be available. So our DP for threshold M includes all subsets with max_ki <= M. So the dp[full] at threshold M is the min cost over subsets with max_ki <= M. But if a subset has max_ki = K, it is included in threshold M for any M >= K. So at M=K, we have it. At M larger, we might have even cheaper subsets. So our candidate total for M=K is Kb + dp[full]_at_K. For M larger, total = Mb + dp[full]_at_M. Since dp[full]_at_M <= dp[full]_at_K, the total might be lower.
Now, is it possible that the optimal total uses a subset whose max_ki = K, but we compute candidate for M=K incorrectly because at M=K, dp[full] might include some other subset with max_ki less than K that has lower sum xi but we might think total = Kb + that lower sum xi, which would be lower than the true cost for the K-subset? Actually if there is a subset with max_ki = K' < K and sum xi = S', then total for M=K (if we use that subset) would be Kb + S'. But we could also set M=K' and pay K'b + S', which is lower because monitors cost less. So the true optimum would be the min across all M, not necessarily the subset's own max_ki. So if dp[full]_at_K includes a cheaper subset with lower max_ki, then candidate at M=K would be Kb + S' which is not the true cost of that cheaper subset (because that subset could be bought with M=K' monitors). But that candidate might be higher than the candidate at M=K' (which is K'*b + S'). Since we take min across M, we will pick the lower at M=K'. So it's fine that dp[full]_at_K includes subsets with max_ki < K. The candidate at M=K may be suboptimal, but the min across M will still get the correct optimum if we also evaluate at M=K'. So it's okay.
But what if the subset with max_ki < K is the one that gives the global optimum? Then we will have candidate at its own max_ki (K') which will be considered. So fine.
Now, consider the possibility that the subset with max_ki < K is not the one giving optimum, but we may inadvertently compute candidate at M=K that is lower than the true optimum? Could that happen? Suppose we have a subset with max_ki = K' < K and sum xi = S'. At M=K, we could still hire that subset because M >= K'. The total cost would be K*b + S'. That's a valid plan: Gena buys M monitors = K and hires that subset. That is a feasible solution: He is allowed to buy extra monitors. So that is a valid total cost. So candidate at M=K is a valid total cost (maybe not minimal, but valid). And we are taking min across all M, so we might end up picking a plan that uses extra monitors unnecessarily? But if that plan is cheaper than any other plan, then it is indeed optimal. Could it be cheaper than using the same subset with fewer monitors? No, because using fewer monitors (M=K') would give total K'*b + S' which is strictly less (since b>0, K' < K). So a plan with extra monitors is always more expensive than using the minimal required monitors for the same subset. So the candidate at M=K for the subset with max_ki=K' is never better than candidate at M=K'. So it won't be selected as min if we also consider M=K'. So fine.
Thus our algorithm enumerates all distinct M (ki values). For each M, we consider the best sum xi achievable using friends with ki <= M. This yields a valid total cost for buying M monitors and using that best subset. The overall min across M gives the optimal cost, because any optimal plan has some M (the max ki of the subset used) and that M is one of the ki values, and its total cost will be considered at that M (since dp[full] at that M will be at most that subset's sum xi, maybe equal). Moreover, if there is a plan with M larger than max ki used, it's suboptimal compared to using the same subset with M = max ki. So we can restrict to M = max ki of used subset. So our enumeration covers all optimal possibilities.
Thus correct.
Now, finalize.
I will output the solution in Python 3. Use fast I/O and optimize loops.
Potential micro-optimizations:
Precompute full = (1<<m)-1.
Use local variables inside the friend loop: dp_local = dp; fm = mask; cost = x; for msk in range(full, -1, -1): cur = dp_local[msk]; if cur != INF: nm = msk | fm; new = cur + cost; if new < dp_local[nm]: dp_local[nm] = new
Use a variable INF = 1<<60.
I'll also consider using array('Q') but not necessary.
Now, test with maximum constraints in mind: 100 * 1,048,576 ~ 105 million. In CPython, this may be too slow. In PyPy, might pass. Many Codeforces problems with similar constraints have PyPy solutions accepted. But to be safe, I could consider a slight optimization: Only iterate over masks where dp[mask] is finite? But we would need to maintain a list of masks that are reachable. Since after many friends, many masks become reachable, it could be near full. So not much savings.
Another optimization: Since we are only interested in dp[full] at group boundaries, we could early exit if dp[full] is already 0? But not likely.
Maybe we can reduce the loop size by using for mask in range(full+1): but then we need to use a temporary array to avoid double counting, but we could also use a technique where we copy dp to newdp and then update newdp, but that would be similar cost.
But there is a known trick: For subset DP with OR, we can use "for mask in range(full+1): if dp[mask] != INF: newmask = mask | fm; newdp[newmask] = min(newdp[newmask], dp[mask] + x)" and then assign dp = newdp. That also does O(2^m) per friend, plus copying O(2^m). That is about double the work. So in-place descending is better.
Thus we keep it.
Now, ensure we use PyPy when running.
Now, finalize solution.
But wait: There is a nuance: In the DP update, we use for msk in range(full, -1, -1). However, the mask variable is an integer. In Python, range(full, -1, -1) will generate full+1 numbers. That's fine.
Now, note that we have to compute dp for each friend. But we could also group friends with same ki together and apply DP for the group using maybe better method? But not needed.
Now, I will produce final answer code.
Before that, check for possible off-by-one: When computing candidate after a group, we use last_ki * b + dp[full]. But what about the case where the very first group (smallest ki) might have dp[full] finite, but we compute candidate only when we encounter next ki or at end. If there is only one group, we compute at end. If there are multiple groups, we compute for each group when moving to next. So for the first group, we compute candidate when we see the second group's first friend. That works. For the last group, we compute at end. So all groups covered.
Now, verify with a scenario where the first group itself yields dp[full] finite, and it's optimal, and there is no second group? Then we compute at end. So fine.
Now, consider scenario where the first group yields dp[full] finite, and it's optimal, but there is a second group. We compute candidate for first group when encountering second group, which is before we have added second group friends. That's fine, because dp[full] at that moment reflects only first group. So candidate computed correctly.
Now, we must also consider the possibility that the optimal M is not among any friend's ki because we might use a subset where max_ki is not present? But max_ki is the ki of one of the friends in the subset, so it's present. So okay.
Now, think about the case where we might not need to buy any monitors because we don't hire any friend? Not possible because we need to solve all problems.
Now, I'll write final solution.
But one more thought: Could there be a scenario where it's optimal to buy monitors but not hire any friend with that exact ki, but the monitors cost is low and the xi sum is lower? Actually if the optimal subset's max_ki = K, then there is at least one friend with ki=K in the subset, because if all friends have ki < K, then max_ki < K, contradiction. So there is some friend with ki=K. So K is among the ki values.
Now, answer.
Now, produce final code with comments for clarity.
We'll write:
import sys
def solve():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
b = int(next(it))
friends = []
for _ in range(n):
xi = int(next(it))
ki = int(next(it))
mi = int(next(it))
mask = 0
for __ in range(mi):
p = int(next(it))
mask |= 1 << (p-1)
friends.append((ki, xi, mask))
friends.sort() # sort by ki
full_mask = (1 << m) - 1
INF = 1 << 60 # sufficiently large
dp = [INF] * (full_mask + 1)
dp[0] = 0
ans = INF
prev_ki = -1
for ki, xi, mask in friends:
if ki != prev_ki:
if prev_ki != -1:
if dp[full_mask] < INF:
total = prev_ki * b + dp[full_mask]
if total < ans:
ans = total
prev_ki = ki
# update dp with this friend
# iterate masks in descending order to avoid using friend multiple times
for cur_mask in range(full_mask, -1, -1):
cur_cost = dp[cur_mask]
if cur_cost != INF:
new_mask = cur_mask | mask
new_cost = cur_cost + xi
if new_cost < dp[new_mask]:
dp[new_mask] = new_cost
# after processing all friends, consider the last ki
if prev_ki != -1 and dp[full_mask] < INF:
total = prev_ki * b + dp[full_mask]
if total < ans:
ans = total
if ans >= INF:
print(-1)
else:
print(ans)
if name == "main":
solve()
We'll use sys.stdin.buffer for faster reading.
Now, test with examples.
Now, final answer.
Potential bug: In the first iteration, prev_ki = -1, we skip candidate calculation. When we encounter first friend with ki = k1, we set prev_ki = k1 and then update dp. But we haven't computed candidate for k1 yet. That's okay, we will compute when we see next ki or at end.
But consider if there are friends with same ki, after processing the first friend, prev_ki = k1, and we haven't computed candidate. We then process second friend with same ki, ki==prev_ki, so no candidate calculation, just update. Good.
Now, after processing the last friend with ki = k_last, we compute candidate at end. So all good.
Now, could there be a scenario where the best solution uses only some subset of friends from a group, but not the entire group? That's captured because dp[full] after processing the entire group is the min over any subset of those friends (including those that don't include some friends). So it's fine.
Now, final answer is ready. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
b = int(next(it))
code
friends = []
for _ in range(n):
xi = int(next(it))
ki = int(next(it))
mi = int(next(it))
mask = 0
for __ in range(mi):
p = int(next(it))
mask |= 1 << (p - 1)
friends.append((ki, xi, mask))
friends.sort() # sort by required monitors ki
full = (1 << m) - 1
INF = 1 << 60 # larger than any possible answer
dp = [INF] * (full + 1)
dp[0] = 0
answer = INF
prev_ki = -1
for ki, xi, mask in friends:
if ki != prev_ki:
# best cost for the previous ki is now known
if prev_ki != -1 and dp[full] < INF:
total = prev_ki * b + dp[full]
if total < answer:
answer = total
prev_ki = ki
# knapsack over subsets: add this friend at most once
for cur in range(full, -1, -1):
cur_cost = dp[cur]
if cur_cost != INF:
new = cur | mask
new_cost = cur_cost + xi
if new_cost < dp[new]:
dp[new] = new_cost
# last group of friends
if prev_ki != -1 and dp[full] < INF:
total = prev_ki * b + dp[full]
if total < answer:
answer = total
if answer >= INF:
print(-1)
else:
print(answer)