We need to parse the problem statement carefully.
We have N reports. AOR Ika-chan can either write each report herself, obtaining score a_i, or copy from one of M friends. If she copies from friend i on report j, she gets the same score as that friend, which is b_{ij}. However, constraints:
- She must not copy on at least K reports (i.e., she must do at least K reports herself). So the number of reports she does herself (i.e., not copying) is >= K.
- Also, for each friend i, she can copy from that friend at most T_i times (i.e., total number of reports where she uses friend i's report is <= T_i). She can copy from at most one friend per report? It says "if you have a report on a theme that you are not good at, you can get the same score as that friend by copying the report of a friend who is good at that theme." This implies for each report, she can choose to copy from exactly one friend, or do it herself. So she can assign each report either to herself or to a specific friend (one of M). The friend's score for that report is given.
- The goal: maximize total score.
Thus we need to choose assignments for each report: either self (score a_i) or copy from some friend i (score b_{ij}) subject to: self-assigned count >= K; and for each friend i, the total copies assigned to i <= T_i.
We need to maximize sum.
N, M, K given. N up to? Not given, but typical constraints maybe 10^5? M up to? Possibly up to 20? But we need to think. T_i are also given. Input format suggests a_i (N numbers), then M lines of N numbers each (b_{ij}), then T_i (M numbers). So N could be large if M is small, but b matrix would be huge if N large and M large. This problem likely from AtCoder? Let's search memory: "AOR Ika-chan" sounds like AtCoder problem? Actually I recall a problem "Report" maybe? Possibly from AtCoder Regular Contest? But I don't recall. Could be from JOI? Need to deduce constraints to design solution.
Since input includes M lines of N numbers, N and M both might be moderate (maybe N up to 2000, M up to 2000?). But if N and M both large, the input would be huge. Could be N up to 200, M up to 200? Let's think.
Alternatively, this is a min-cost flow or assignment problem? We can think: For each report, we have multiple options: self or each friend. We have capacity constraints per friend, and a lower bound on self count. This is a typical bipartite matching with constraints, can be solved via max cost flow (or min cost negative). Since each report must be assigned exactly to one "source" (self or one friend). Self has unlimited capacity (or capacity up to N, but lower bound). Actually we require at least K self. That's like a constraint: number of self assignments >= K. To handle lower bound, we can convert: we could decide self assignments count S >= K, we could treat self as a special friend with capacity unlimited but we need to enforce at least K. Equivalent to we can choose to assign some reports to self, but we are forced to assign at least K. That's like we can always assign to self if we want, but we must have at least K self. So we can think of a max cost flow where we have a sink for reports, and sources: self and each friend. The self source has supply N? Actually each report picks one source. So it's assignment from reports to sources with costs (negative scores) and capacities: each friend i can supply at most T_i, self can supply any number but we need at least K self? Actually we need exactly N assignments. The number of assignments to self must be at least K. This is a lower bound on flow from self to reports. In min-cost max-flow, we can set self source with lower bound K and upper bound N. But we can also handle by initial forcing K self assignments and then optionally more.
Alternative approach: For each report, the benefit of copying from friend i compared to doing self is (b_{ij} - a_j). Actually we want to maximize sum. So we could think: base sum is sum of all a_i (if we do all self). Then for each assignment to a friend, we get an extra gain of (b_{ij} - a_i). So we want to pick up to (N - K) copies (since we need at least K self, so maximum copies = N - K) and assign them to specific reports and friends, but subject to friend capacities T_i. Also we can also decide to not copy a report (i.e., do self) even if we have capacity left; it's optional.
But careful: We must have at least K self, but we could have more than K self; i.e., we don't have to use all copy capacities. So we want to select a set of reports to copy (maybe up to N - K copies, but could be less) and assign each to a friend i with capacity T_i, to maximize total gain. Since base sum is sum a_i, maximizing total sum = base sum + max total gain from copies (where each copied report gives gain g_{ij} = b_{ij} - a_i). However, if g_{ij} is negative, we wouldn't want to copy that report, because we can just do self and get higher. But note: If we need to meet the minimum self count K, we could also copy even if gain negative? Actually we must have at least K self, so we can't copy more than N - K reports. If we copy a negative gain report, total sum decreases. Since we have no requirement to copy any reports, we would never copy a negative gain report. So we only consider positive gains (or zero? zero gain doesn't matter, could copy or not). So the problem reduces to: we have a set of possible copy assignments (i, j) with gain g_{ij} = b_{ij} - a_j. We want to select at most C = N - K copies (since we need at least K self, so max copies = N - K). Actually "not copying someone else's report at least K out of N times" means "you have to finish the report yourself, not copying someone else's report at least K out of N times." So the number of self-done reports (not copied) is >= K. That means copied reports <= N - K. So yes, maximum copies allowed is N - K. However, we also have per-friend copy limit T_i. Also, each report can be copied at most once (or not at all) and from at most one friend. So we need to choose a set of copies that is at most one per report, each copy uses capacity of the friend, total copies <= N - K. Maximize sum of gains.
If we think of base sum = sum a_i, then answer = base sum + max achievable total gain.
Now this is a combinatorial optimization: we have N reports, each can be assigned to at most one friend (or none). For each friend i, we can assign up to T_i reports. We can assign up to L = N - K total assignments. Each assignment yields a gain g_{ij}. We want max total gain.
This looks like we can treat it as: we have M friends, each with capacity T_i, and we have a set of candidate assignments. We need to pick at most L assignments, respecting per-friend capacities, and at most one per report. This is essentially a maximum weight bipartite matching with a global cardinality constraint (total number of matches <= L). And also capacities per left side (friends) are limited. Actually it's a bipartite graph: left side = friends (each with capacity T_i), right side = reports (each with capacity 1). But we also have a global constraint: total matches <= L. However, the capacity of right side is 1, so total matches is automatically <= N. But L may be less than N, so we may not be able to take all positive gains if there are more than L. So we need to limit total matches.
We can convert this to a min-cost flow problem: source -> friends (capacity T_i, cost 0), friends -> reports edges (capacity 1, cost = -g_{ij}) (or we want max gain so negative cost), reports -> sink (capacity 1, cost 0). Additionally, we need to limit total flow to at most L. In min-cost max-flow, we usually push as much flow as possible to minimize cost. But here we want to push up to L flow, but may not push all if negative costs? Actually we want to maximize gain, so we only want positive gains. But if we include edges with negative gains, we wouldn't take them. So we can just not include those edges (or they won't be selected because we can choose flow amount). So we can consider only edges with positive g_{ij} (or zero). Then we want to send flow f <= L from source to sink through these edges, with cost = sum of -g. Minimizing total cost = -max gain. So we can set cost = -g for edges, and then find min cost for sending flow up to L, but we also can decide f < L if there are not enough positive edges? Actually we want maximum total gain, so we would take as many positive gains as possible, but limited by capacities and L. So we want to find the max total gain achievable with at most L assignments. This is like a knapsack but with bipartite structure; but flow can solve it: we can add a dummy edge from source to sink? Or we can treat it as we want min cost for exactly L flow? But maybe we might not have enough positive edges to send L flow; then we can send as many as possible (i.e., max flow) but limited by positive edges and capacities. However, the problem states we can also choose not to copy; if there are not enough positive gain assignments, we just take those positive ones. So we want to maximize gain, which is equivalent to sending flow up to L but not forced to exactly L; we can send any amount <= L. In min-cost flow, we can achieve that by gradually augmenting flow while cost is negative (i.e., gain positive), stopping when next augmenting path would have non-negative cost (i.e., gain <=0). So we can do successive shortest augmenting path (SSAP) until we have sent L flow or no negative-cost path exists.
But we need to be careful: The network: source -> friend i (capacity T_i, cost 0). friend i -> report j (capacity 1, cost = -g_{ij}) if g_{ij}>0 (or include all but treat negative as high cost? Better to include only positive). report j -> sink (capacity 1, cost 0). Then we want to send flow from source to sink. The total flow will be number of copies. Each unit of flow yields a gain = -cost. We want to maximize total gain, i.e., minimize total cost. Since costs are negative for positive gains, sending flow reduces total cost (makes it more negative). The min-cost flow for a given flow amount f is the one that picks the f best gains (subject to capacities). So we can run a min-cost flow algorithm that supports sending flow incrementally, and we stop when either we have sent L flow, or the shortest path from source to sink has non-negative cost (i.e., no more beneficial assignment). Because if the shortest path cost is >= 0, then sending more flow would not increase gain (or decrease total sum). Actually note: In min-cost flow, costs can be negative, but there may be negative cycles? With these edges, no cycles because graph is acyclic? Actually there could be cycles through source? But typical min-cost max-flow with negative costs on edges requires handling potentials (Johnson) to avoid negative cycles. But with bipartite structure, if we use potentials, it's fine. However, we can also transform to max weight matching using a greedy approach: Since each report can be assigned to at most one friend, and friends have capacities, and we have global limit L, we can think of sorting all possible assignments by gain descending, and then selecting them greedily while respecting constraints. But greedy may fail because of conflicts (one report can only be assigned to one friend). However, if we use a matroid intersection? This is essentially a bipartite matching with capacities, which is a matroid? Actually the set of assignments that are matchings forms a transversal matroid? But with capacities, it's a bipartite b-matching. The problem of selecting a set of edges with maximum total weight subject to degree constraints is a classic maximum weight b-matching in bipartite graphs. That can be solved via min-cost flow or Hungarian algorithm with multiple assignment. Since N and M might be up to maybe 200, we could do min-cost max-flow with nodes up to N+M+2. If N up to 10^5 and M up to 10, we could maybe handle? The number of edges: MN if we include all possible copy edges; that could be huge if N large and M moderate. However, we can note that we only care about positive gains; but still worst-case could be all positive. So we need to handle potentially large N, but M may be small. The problem statement: "AOR Ika-chan is taking a class where grades are determined only by the score of the N report." Possibly N up to 10^5? M up to maybe 20? Because they have M friends, T_i up to N. Input b matrix is M lines each with N numbers. That would be up to MN numbers. If N=10^5 and M=20, that's 2e6 numbers, which is borderline but maybe acceptable in some contests (2 million integers). However, typical AtCoder problems might have up to 2000 each? I'd need to search memory: There's an AtCoder problem "AOR" something? Actually I recall a problem "AOR Ika" from JOI 2018? Not sure.
Given we are to write a solution, we need to consider efficiency. If N is large (like up to 200,000) and M is small (like up to 20), we could do a greedy approach using priority queues: For each report, we have best gain among friends? But we have capacity constraints, and we also have total limit L. This resembles a scheduling or selection problem: we have M machines (friends) each can process up to T_i jobs (reports), each job j if processed by machine i yields gain g_{ij}. We want to select up to L jobs to assign, maximizing total gain, with each job assigned at most once.
We could treat each friend independently, selecting the best T_i reports for that friend, but there may be conflicts if a report is best for multiple friends. So we need to decide assignment.
One approach: min-cost flow is classic and works for moderate sizes. But with N up to 2000 and M up to 2000, edges would be up to 4 million, which is okay for min-cost flow with potentials and Dijkstra? Might be heavy but possible if N and M are 2000. However, typical min-cost flow with O(F * (V log V + E)) where F is flow value (up to L ≤ N). If N=2000, that could be 2000 * (4000 log 4000 + 4e6) which is too high. But we can use successive shortest augmenting path with potentials; but the number of augmentations equals the flow we send. If we send up to N (2000) augmentations, each with Dijkstra on graph of V ~ 4000 and E up to 4e6, Dijkstra with adjacency list and binary heap O(E log V) per augmentation => 2000 * 4e6 log 4000 ~ 8e9 operations, too slow.
Thus we need a more efficient method, perhaps using capacity scaling or cost-scaling? But maybe constraints are smaller. Let's try to locate the problem. Perhaps it's from AtCoder Grand Contest? I'm trying to recall any problem with "AOR Ika". Actually "AOR" might be a pun on "AORU" (to copy?) Not sure.
Maybe it's from JOI 2020/2021? There is a problem "Report" that involves copying friends? I think there is a known problem: "AOR" stands for "AORU" meaning "to copy"? Possibly "AOR Ika" is a character. I recall an AtCoder problem "A - AOR" maybe? Hmm.
Let's think about the constraints from input format: first line N M K. Then a_i line (N numbers). Then M lines of N numbers each b_ij. Then T_i line (M numbers). So total numbers = 1 + N + M*N + M = roughly (M+1)*N + M +1. If N and M are both up to 100, that's ~10k numbers. If up to 500, that's 250k numbers. If up to 1000, that's about 1e6 numbers. That's plausible.
But typical problems with matrix input often have N up to 200 and M up to 200. Alternatively, they might have M up to 20 and N up to 2000. Could be either.
Given that we are ChatGPT and need to produce code that solves the problem efficiently for typical constraints, we might design a solution using min-cost flow but optimizing with the fact that M is small, so we could compress the graph by having each report node but edges to M friends. That would be M*N edges. If N is up to 10^5 and M up to 20, that's 2e6 edges, which is large but manageable for flow? Flow algorithms on graphs with 100k nodes and 2e6 edges might be heavy, especially if we need to run many augmentations. However, we could use a min-cost flow algorithm that uses successive shortest paths with potentials, and each augmentation will add one unit of flow. In the worst case, we might augment up to L, which could be up to N (10^5). That would be 10^5 Dijkstra runs on graph with ~120k nodes and 2e6 edges -> maybe 10^5 * (2e6 log 120k) impossible.
So we need a different approach.
Maybe we can treat it as a max weight matching in a bipartite graph with capacities on left, but we could convert to an assignment problem with "virtual copies" of friends. If each friend i can be used T_i times, we can create T_i copies of friend i, each can be assigned to at most one report. Then we have a bipartite graph between reports and friend copies, with edges weighted by gain. Then it becomes a maximum weight matching in a bipartite graph, with number of nodes on left side = total capacity sum T = sum T_i, on right side = N. But we also have global limit L: we cannot match more than L reports (i.e., we don't have to match all reports). So we need to select at most L matches. That can be handled by adding dummy nodes with zero weight, or just we can stop when we have selected L matches.
However, sum T_i could be large (up to NM maybe). If T_i each up to N, sum T_i up to NM, which could be huge. But maybe T_i are small? The problem statement: "she decided to copy the report to her friend i less than T_i times." So T_i is an upper bound; could be large. So copying virtual copies may blow up.
Alternatively, we can use a greedy algorithm that for each report, we consider its potential gain if assigned to a friend, and we have to select which reports to copy and assign. This is similar to: we have M friends, each with capacity T_i. For each report j, we have M possible gains g_{ij}. We can think of assigning reports to friends to maximize sum of gains, with capacity constraints, and then we also have the option not to assign the report (gain 0). And we have an upper bound on number of assignments: total assignments <= L. But since not assigning yields zero gain, the optimal solution will assign exactly some number up to L, only those with positive gains.
This is essentially a maximum weight b-matching with a limit on total matches, but we can ignore the limit if we ensure we never exceed L, but if the sum of capacities of friends may exceed L, we need to limit to L.
We can incorporate L as an additional "source" capacity limit.
One way: Use min-cost flow with source -> friends capacities T_i, friends -> reports edges (cost -g), reports -> sink capacities 1, and then also set a capacity on the source-sink? Actually we can set a global limit L by adding a "super source" that has supply L, and also an edge from original source to sink with infinite capacity and zero cost? Wait.
Standard technique: To limit total flow, we can add an edge from source to sink with capacity L and cost 0, and then run min-cost flow? That doesn't work because flow could bypass friends? Actually we want flow that goes through friends->reports, not directly. So we can create a node S, connect to friends, then friends->reports->sink, but we want to limit total flow from S to sink to L. We can just set the supply at S to L (i.e., we push exactly L flow, but we can also not use all if edges have positive cost? However, we want to allow less than L if beneficial? But pushing less than L when costs are positive (i.e., negative gains) would be detrimental: we want to stop when additional gains are non-positive. If we force exactly L flow, we might be forced to take negative gains. So we need to allow flow less than L. So we can treat it as a min-cost flow where we augment until either flow = L or no negative-cost augmenting path exists. So we can just run successive augmentations with Dijkstra and stop when condition met.
But as noted, augmenting one by one may be too slow if L is large. However, we can use capacity scaling or cost-scaling but that's complex. Alternatively, we can use a min-cost max-flow algorithm that handles multiple units with potentials and we can send flow along multiple shortest paths if they share costs? Not directly.
But perhaps L is not extremely large? If N is at most 2000, L <= 2000, augmenting 2000 times might be okay if each Dijkstra is on a graph of about N+M+2 ~ 4000 nodes and M*N edges (up to 4e6). Dijkstra with binary heap on dense graph would be O(E log V) ~ 4e6 * log(4000) ~ 4e6 * 12 = 48e6 per augmentation. 2000 * 48e6 = 96e9, too high.
But maybe we can reduce edges by not including all possible edges. Since M is small, we can represent for each report the top gains? But we need to consider all gains for optimal assignment, because a report might be assigned to a friend with not top gain if top gains are taken by others. However, we can use a primal-dual algorithm for assignment with capacities on one side. This is similar to the "assignment problem" where left side (friends) have capacities >1. We can treat each friend as having T_i copies, but we can use a min-cost flow with cost scaling that runs in O((N+M) * something). There is also the Hungarian algorithm for rectangular assignment, which can be extended to capacities by duplication but that would be large.
Maybe we can solve using a greedy algorithm with priority queues: For each friend i, we can precompute the gains for all reports, sort descending. Then we need to assign reports to friends, each report can be assigned to at most one friend. This is reminiscent of a problem: given M machines with capacities, each job has profit on each machine, assign jobs to maximize profit. It can be solved by a maximum weight matching in bipartite graphs, but if M is small, we could use DP? Not easily.
Another perspective: Since each report can be assigned to at most one friend, we can think of selecting which reports to copy and which friend to assign. This is like a combinatorial optimization that can be reduced to a maximum weight independent set in a certain hypergraph? Not.
We could treat it as a minimum cost flow and use successive shortest augmenting path, but we can accelerate by sending more than one unit of flow per augmentation when edges have unit capacity? Most edges have capacity 1 (friends->reports) so each augment sends exactly 1 unit. So we need L augmentations in worst case. So complexity is O(L * (E log V)). That could be acceptable if L is small or E is small.
Maybe constraints are such that N and M are moderate (≤ 200). For N=200, M=200, edges = 40,000, L ≤ 200, then per Dijkstra maybe 40k * log(400) ~ 40k * 9 = 360k, times 200 = 72 million, feasible. So maybe that's the intended solution.
Given typical AtCoder problems with a matrix input, N and M often up to 200. Also note that T_i are given but no explicit sum. Could be up to N.
Let's search memory: There is a problem named "AOR Ika" on AtCoder? I quickly recall an AtCoder problem "A - A + B" but not. Actually there is a problem "AOR" maybe from JOI 2021 Spring? I'm not sure.
Alternatively, this problem might be from "JOI 2018/2019" something. I remember a problem "Copying" with friends and reports. Could be from AtCoder Beginner Contest? I think it's from AtCoder Regular Contest 112? Not sure.
Given the time, maybe we can design solution using min-cost flow with potentials, and hope constraints are moderate.
But wait, we also have to handle the base sum a_i, and we subtract that. Actually we could compute gains. But note that if we decide to copy a report, we lose the a_i and gain b_{ij}, so net gain is b_{ij} - a_i. That could be negative. So we can simply include only edges with positive gain, because we would never copy a report with negative gain because we have the option not to copy (self) and we need at least K self but we can have more self; negative gain would reduce total, so not selected.
Edge case: If there are not enough positive gains to satisfy the requirement of at least K self? Actually requirement is only lower bound on self; we don't need to copy any. So we can just ignore negative gains.
Thus we can filter edges.
Now, what about the case where we might be forced to copy some reports with negative gain because we must not copy more than L? Actually we are not forced to copy any; we can choose to copy fewer than L. So we never copy negative gain.
Thus we only consider positive gains.
Now min-cost flow: nodes: source (0), friend nodes (1..M), report nodes (M+1 .. M+N), sink (M+N+1). Edges: source -> friend i (capacity T_i, cost 0). friend i -> report j (capacity 1, cost = -g_{ij}) if g_{ij}>0. report j -> sink (capacity 1, cost 0). Then we want to send flow up to L, but we can also send less if no more negative cost paths.
We need to handle the fact that we have also the self option which yields 0 gain and does not consume any capacity. But we don't need to model it explicitly because not copying is equivalent to not assigning that report to any friend, i.e., not sending flow through that report node. However, we also need to ensure that we have at least K self reports. That is equivalent to at most L copies. So as long as we send at most L flow, we satisfy self >= K. In the flow model, we don't enforce a minimum flow; we simply send as much beneficial flow as possible but not exceed L. That's fine.
But there is a nuance: What if we want to not copy a report even though it has positive gain? Could that ever be optimal? Possibly if we need to leave capacity for a higher gain report on the same friend? But we are maximizing total gain; if a report has positive gain, we would want to copy it unless it prevents a higher gain later. That's the matching conflict: a friend has capacity T_i, so we might have to choose which reports to assign to that friend. That is captured by the flow: we choose at most T_i edges from friend i, and each report can be assigned to at most one friend. So if we include an edge for a report with positive gain, it may be excluded if we need to pick a different assignment for that friend to maximize sum. The flow will choose the optimal set.
Thus the flow model correctly captures the optimization.
Now we need to implement min-cost flow that can handle up to perhaps 2000 nodes and 400k edges? Let's compute: If N=2000, M=200, edges friend->report = M*N = 400k. That's large but maybe acceptable in C++ with adjacency list. Dijkstra each iteration would be O(E log V) = 400k * log(2200) ~ 400k * 11 = 4.4M per augmentation. If L=2000, total ~ 8.8 billion, too high. So maybe M is smaller.
Alternatively, maybe M is up to 20. Then edges = 20 * 2000 = 40k, which is okay. Dijkstra per iteration 40klog(2020) ~ 40k11=440k, times L=2000 = 880M, still a bit high but maybe borderline in C++ with optimizations? 880M operations might be too slow. But maybe N=1000, M=10, edges=10k, L=1000, then 10M per iteration? Actually 10klog(1010)~10k10=100k, times 1000 = 100M, might be okay in C++ with optimized code. In Python, it would be too slow.
Given we are writing in Python? The problem statement asks for code? Usually ChatGPT solutions are in Python. However, typical competitive programming problems often have constraints that allow Python solutions with efficient algorithms. If we implement min-cost flow in Python with 40k edges and 1000 augmentations, that could be borderline but possible if using heaps and adjacency list, but 100M operations might be too slow for Python. So maybe constraints are smaller.
Perhaps there is a more clever greedy solution. Let's consider if M is very small, we could use DP over subsets? Not.
Another thought: This is essentially a maximum weight bipartite b-matching, which can be solved via Hungarian algorithm extended to multiple assignments by converting each friend to T_i copies. If sum T_i is not huge, we can do Hungarian with O((sum T_i)^2 * N) maybe? That could be large.
We can also think in terms of linear programming and use a greedy approach: sort all edges by gain descending, and then attempt to assign each edge if possible (like a matroid intersection). The constraints: each friend capacity (like a partition matroid on friend assignments), each report at most one (a partition matroid on reports). The set of assignments that are matchings form the intersection of two partition matroids. The maximum weight independent set in the intersection of two partition matroids can be found by a greedy algorithm? Not exactly; for matroid intersection, there is an algorithm using augmenting paths, which is essentially the same as finding a maximum weight common independent set. For two matroids, there is a polynomial algorithm based on augmenting paths, but it's not simple greedy. However, if we treat edges sorted by weight descending, we can use the concept of "maximum weight matching in bipartite graph" which is exactly the intersection of two partition matroids. There is a known greedy algorithm for bipartite matching? No, greedy by weight does not work for matching because of conflicts.
But we can use a variant: For each report, we can consider the best gain among friends, but we need to allocate capacities. This is akin to "assignment problem" which is solved by Hungarian algorithm or min-cost flow. So min-cost flow seems the natural solution.
Given typical problem constraints, I'd guess N ≤ 200, M ≤ 200, or N ≤ 500, M ≤ 500, but then edges = 250k. L ≤ N = 500, augmentations=500, each Dijkstra O(E log V) = 250k*log(1000)=2.5M, total 1.25B, too high. But maybe we can improve by using a potential function and using Dijkstra on a graph with many edges, but we can also use the fact that edges from friends to reports have cost that is negative of gain. However, we can also consider using successive shortest path with potentials, but we might be able to batch multiple augmentations? Since all edges from source to friends have capacity T_i, we can send multiple flow through a friend if many reports have positive gains. But each report node capacity is 1, so augmentations are still unit.
Maybe we can use a "min-cost max-flow with scaling" or "cost scaling" algorithm, but implementing in Python is heavy.
Another approach: Because M is small, we could use DP over number of copies per friend? Not, because reports are many.
We could use a "Hungarian algorithm" where we treat each friend as having multiple slots, but we can also use a "minimum cost flow" but we can reduce the graph by using a "node for each report" and a "node for each friend" with capacity, and then use a "successive shortest path" but we can also implement using "SPFA" for negative costs? But we can transform costs to non-negative using potentials, but we have negative edges initially. However, we could use the "Successive Shortest Augmenting Path" algorithm with Bellman-Ford initially to compute potentials, then Dijkstra each step. That's standard.
Given the constraints unknown, we need to design a solution that is efficient enough for typical input sizes in Python. Perhaps we can do the following: Since M is small (maybe ≤ 20), we can use a "minimum cost flow" but we can also use a "max weight assignment with branch and bound"? Not.
Maybe we can treat this as a "knapsack" with each report being an item that can be assigned to one of M friends or not. This is a kind of multi-dimensional knapsack? Not.
Alternatively, we could use a "Lagrangian relaxation" or "greedy with priority queue for each friend", but need to resolve conflicts. There is a known algorithm: For maximum weight matching in bipartite graphs where one side has capacities, we can use a "min-cost flow" but we can also use a "greedy" approach if we process reports in decreasing order of maximum gain, and when a conflict arises (a report could be assigned to a friend that is already full), we consider swapping? That's like the "greedy matching" that is not optimal.
But we could use the "assignment problem" solved by the "Hungarian algorithm" with O(N^3). If N is up to 500, O(500^3)=125M, which is okay in C++ but maybe heavy in Python. But here N could be up to 2000? That would be 8e9, impossible.
Maybe we can transform to a max weight bipartite matching where left side are reports? Actually we have N reports and M friends, but friends can take multiple reports. This is a "maximum weight bipartite b-matching". There is an algorithm that runs in O(N^2 M) or similar using potentials. Actually the Hungarian algorithm can be adapted to rectangular matrices with multiple assignments by adding dummy rows/columns, but that would increase size to sum T_i.
Let's try to deduce constraints from the example: N=3, M=2, K=2. So small.
I think the most plausible is that N and M are ≤ 200. That would make min-cost flow feasible in Python if implemented efficiently? 200*200=40k edges, 200 augmentations, each Dijkstra with binary heap on 400 nodes and 40k edges. 40k edges is actually not that many; Dijkstra's complexity is O(E log V), but with adjacency list, each edge considered once. 40k * log(400) ≈ 40k * 9 = 360k per Dijkstra. 200 * 360k = 72 million operations, which in Python might be borderline but could pass with good code (using heapq). 72 million operations (like pushing and popping) might be okay if optimized? Actually Dijkstra's algorithm will for each edge do a relaxation which may lead to a heap push/pop. 360k operations per run, 200 runs -> 72 million heap operations; each heap operation is O(log V) but the constant is moderate. 72 million might be a bit high for Python but maybe within 2 seconds? Possibly if time limit is generous. But also building the graph and other overhead.
But if N=500, M=500, edges=250k, then per Dijkstra 250klog(1000)=250k10=2.5M, 500 augmentations => 1.25B, impossible in Python. So constraints likely smaller.
Given the problem statement and typical AtCoder problem, I recall a problem named "AOR Ika" maybe from AtCoder Beginner Contest? Actually I found a memory: There is an AtCoder problem "ARC 106 B" but not. I'll search my mental database: "AOR Ika" might be from JOI 2020/2021? I think I've seen this problem before: "AOR Ika-chan" appears in JOI 2019/2020? Possibly from JOI 2021? I recall a problem about copying reports with constraints N <= 200, M <= 200. Let me think: JOI 2020/2021 has a problem "Copy and Paste" but not.
Better approach: Let's analyze problem structure further to see if there is a simpler solution.
We have base sum S = sum a_i. We need to pick at most L = N - K copies to maximize gain. This is like we have a set of items (j, i) with value g_{ij} (positive). We need to select a subset such that each j appears at most once, each i appears at most T_i, and total selected ≤ L. This is a classic "b-matching with cardinality constraint" which can be solved by a min-cost flow. So that's likely intended.
Given that the input includes the whole b matrix, it's natural to have N and M moderate because they need to input that matrix. So constraints are likely N <= 200, M <= 200, or maybe N <= 1000, M <= 100. AtCoder often has problems with N up to 200 and M up to 200 for such input.
We could also use a "max flow with costs" using the successive shortest augmenting path algorithm. That's doable.
But there is also the possibility of using "minimum cost flow" with capacity scaling where we can push multiple units along the same path if capacities allow. However, the critical edges (friend->report) have capacity 1, so we can't push more than 1 per edge. But we could push multiple units from a friend to different reports via different paths, but they share the source->friend edge which has capacity T_i. We could push multiple flows from source to friend simultaneously by augmenting each time. However, we could compute the shortest path tree and then push as much flow as possible along all augmenting paths of the same length? That's not straightforward.
Another optimization: Since all edges from source to friends have cost 0, and all edges from reports to sink have cost 0, and friend->report edges have costs -g_{ij}. The graph is bipartite. We can use the Hungarian algorithm for unbalanced assignment? Actually Hungarian algorithm solves assignment where each left node is assigned to exactly one right node (or one-to-one). Here we have multiple assignments per left node (friend) and each right node (report) can be assigned at most once. This is a "rectangular assignment" with capacities on left. Hungarian can be extended to handle multiple assignments by creating multiple copies of each left node. But if T_i sum is not huge, we could do that. However, T_i could be up to N, so sum T_i could be up to N*M which could be large.
If M is small, we could treat each friend's capacity as separate slots, but that would be many slots. But we could also treat it as a "minimum cost flow" with a small number of left nodes, which is good.
Given M might be small, we can use a "min-cost max-flow" with Dijkstra using potentials, and also we can use "SPFA" for each augmentation because the graph has negative edges initially but after potentials it's non-negative. However, we can also use "cost scaling" but not.
Alternatively, we could use a "primal-dual" algorithm for min-cost flow specifically for bipartite matching: we can treat it as a min-cost flow and use successive shortest augmenting path, but we can accelerate by using a "Dijkstra with potentials" that uses the fact that the graph is bipartite and costs are only on edges from friends to reports. We could also use a "min-cost flow" using "cost-scaling" but that's overkill.
Another possibility: Use "minimum cost flow" with "capacity scaling" but still augment one unit per augmentation for unit capacity edges.
Given the typical constraints for such problems on AtCoder where Python is accepted, they might keep N and M <= 100, so that O(NM * min(N, sum T_i)) is okay.
I should search for the problem to know exact constraints. Since I don't have internet, I'll try to recall: I think I've seen a problem "AOR Ika-chan" on AtCoder: actually there is an AtCoder problem "AOR" is a company? I recall a problem "A - AOR" maybe from JOI 2020? I'll think: In JOI 2020/2021, there is a problem "AOR" stands for "AORイカちゃん"? It might be from JOI 2019? Let's check: JOI 2019/2020 season? There's a problem "Copying" but not.
Another approach: Let's design a solution that works for moderate sizes, and hope it passes. We'll implement min-cost max-flow with successive shortest augmenting path using potentials (Johnson's reweighting) and Dijkstra with heapq. We'll also add early termination when the shortest distance from source to sink becomes non-negative (i.e., no more negative cost paths, meaning no more positive gain). Actually costs are negative for beneficial edges, so the shortest path distance (min cost) could be negative as long as there's a beneficial assignment. Once the shortest path cost >= 0, further flow would not increase total gain (would decrease or not change). So we stop.
We need to be careful about negative cycles: The graph may have no cycles because it's a DAG? Actually source->friend->report->sink is a DAG, so no cycles, so potentials work fine.
Now, implementation details:
-
Let V = M + N + 2.
-
Node 0: source, node 1..M: friends, node M+1 .. M+N: reports, node M+N+1: sink.
-
Add edge source -> friend i: capacity T_i, cost 0.
-
For each friend i and report j, compute gain = b[i][j] - a[j]. If gain > 0, add edge friend i -> report (M+j): capacity 1, cost = -gain (since we want min cost).
-
Add edge report j -> sink: capacity 1, cost 0.
We also might add edge from source to sink? Not needed.
Then run min_cost_flow_up_to_L.
We also need to handle that we might have positive gain edges but flow might be limited by L. So we will augment flow while flow < L and there exists a path with negative total cost (i.e., distance < 0). Actually we want to augment only if the augment reduces total cost (i.e., negative cost path). Since all costs are non-positive? Actually costs are 0 or negative. So the shortest path distance will be negative if there's any edge with negative cost reachable. Since we add only positive gain edges, they have negative cost. So as long as there is any such edge, the shortest path will be negative? Not necessarily if all paths go through an edge with negative cost, then yes the total cost will be negative. But if all remaining edges from friends to reports are not available (capacity 0) or no more capacity from source to friends, then no path. So we can run while flow < L and there exists a path from source to sink (i.e., distance < INF) and distance < 0 (if we only want to increase gain). However, if distance == 0, that would mean using zero-gain edges (which we might have omitted if gain = 0). If we include zero-gain edges, they don't affect total sum, but we don't need to take them. So we can stop when distance >= 0.
But careful: The distances are computed using potentials, so they reflect the reduced costs. The actual cost of the path is distance + potential(sink)-potential(source). But typically we maintain potentials such that reduced costs are non-negative. Initially, we can set potentials to 0 and run Bellman-Ford to compute initial potentials because there are negative edges. However, since graph is DAG and we have no negative cycles, we can compute initial potentials via Bellman-Ford or just set potentials to 0 and use SPFA for first iteration? But standard min-cost flow with potentials uses Dijkstra only if reduced costs are non-negative. We can initialize potentials with Bellman-Ford from source to compute shortest distances, which will handle negative edges. Then we can use those as potentials, and thereafter Dijkstra works because reduced costs become non-negative.
Simpler: Since all negative costs are on edges from friends to reports, we can transform costs by adding a constant to make them non-negative? But not constant per edge.
Alternatively, we can use a "successive shortest path" algorithm that uses Bellman-Ford (or SPFA) each iteration because the graph is small. With moderate graph size, we could use SPFA each iteration; if N and M <= 200, edges up to 40k, SPFA might be okay for 200 iterations? In worst case, SPFA could be O(VE) per iteration, which for V400, E40k gives 16 million per iteration, 200 iterations => 3.2 billion, too high. So better to use Dijkstra with potentials.
We'll implement min-cost flow with potentials.
Now, about graph size: We'll have up to M*N edges for positive gains. But we can prune: only add edges where gain > 0. That reduces edges.
Now, regarding L: L = N - K. If K is small, L could be large, up to N. So we may have many augmentations.
But we can also combine multiple augmentations by noticing that we have a bipartite graph with unit capacities on the middle edges. However, we might be able to use a "min-cost max-flow" algorithm that finds the minimum cost for each possible flow using successive shortest augmenting paths; that's what we do.
We might speed up by using "cost scaling push-relabel" but that's complex.
Given that Python might be too slow for large cases, we could implement in C++ if required, but as ChatGPT we usually provide Python code. The problem likely expects a Python solution? Not sure.
Maybe there's a different solution: Since M is small, we can use DP over subsets? Not.
Another thought: This problem can be reduced to a "maximum weight matching in a bipartite graph with capacities on left" which can be solved by a "min-cost flow" but there is also a "Hungarian algorithm" variant for rectangular matrices if we duplicate left nodes. If sum T_i is not too large (maybe sum T_i is at most something like 2000), then we could do Hungarian with O((sum T_i)^2 * N) but that could be large.
But note: T_i are given, but they could be as large as N. So sum T_i could be up to N*M. That's too large.
Perhaps constraints ensure that sum T_i is not huge? But T_i could be up to N, but if M is small, sum T_i is M*N, still large.
But we don't necessarily need to duplicate; we can treat each friend as having capacity T_i and use the "min-cost flow" which is efficient.
Given the uncertainty, I'll implement a min-cost flow in Python with careful optimizations: use adjacency list with edge objects, use heapq for Dijkstra, and potentials.
We need to be careful about recursion limit? Not.
Also, we need to compute base sum: total = sum(a_i) + max_gain.
Now, note: The edges from source to friends have capacity T_i, but T_i could be 0, then no edges. Also, we must ensure that total flow cannot exceed L; we'll stop after L augmentations or when no negative-cost path.
Implementation steps:
- Read N, M, K.
- Read list a (length N).
- Read M lines of b_ij (each length N). We'll store as list of lists.
- Read list T (length M).
- Compute base = sum(a).
- For each i in 0..M-1, for each j in 0..N-1, compute gain = b[i][j] - a[j]. If gain > 0, we will add an edge from friend i to report j with capacity 1 and cost = -gain. We'll store these edges.
But if we store all edges, that's M*N. If M=200, N=2000, that's 400k edges. That's okay memory wise (400k edges, each edge stored twice for reverse, so 800k edges). In Python, each edge as a tuple or object might be memory heavy but still manageable (maybe 20 bytes per edge? 800k edges -> 16 MB). Might be okay.
But we also need to store adjacency list. That's fine.
Now, min-cost flow algorithm:
We'll implement a class Edge: to, rev, cap, cost.
Graph: list of list of edges.
Add edge function: forward edge with cap, cost; reverse edge with 0, -cost.
Potentials: array h of size V, initially 0. But we have negative costs, so we need to compute initial potentials to ensure reduced costs non-negative. We can compute the shortest distances from source using Bellman-Ford (or SPFA) once before starting augmentations, because after that all reduced costs become non-negative if we maintain potentials correctly.
However, Bellman-Ford on V nodes and E edges: V up to maybe 2200, E up to 800k? That's heavy: 2200 * 800k = 1.76e9 operations. That's not feasible. But we can avoid Bellman-Ford if we initialize potentials with 0 and then use Dijkstra with negative edges? Dijkstra doesn't work with negative edges. But we can use SPFA for the first iteration only, but SPFA might be okay if we run it only once and the graph is not huge? 800k edges, 2200 nodes, SPFA could be okay because it's essentially BFS with queue; worst-case could be high but often passes. However, we can also initialize potentials differently: Since the graph has no negative cycles, and all negative cost edges are from friends to reports, we can set initial potential for friend nodes to 0 and for report nodes to something? Another trick: We can set the cost of edges friend->report to negative, but we can add a constant to make them non-negative? Not constant because each edge has different gains. However, we can shift costs by adding a large constant to all friend->report edges to make them non-negative, then subtract that constant times flow later. Since all those edges have capacity 1, if we add a constant C to each such edge, the total cost of any flow will be increased by C * flow. If we then subtract C * flow from the final cost, we get the original cost. But we also need to ensure that the shortest path respects the constant. But we could set C = max_gain? Actually we want to make costs non-negative. Since gains are positive, -gain is negative. If we add a constant big enough, say MAX_GAIN (the maximum gain among all edges), then -gain + MAX_GAIN >= 0. But we need to subtract later. However, this changes the relative costs because the constant added is the same for all edges, so ordering of paths may change if paths have different numbers of friend->report edges? But each path from source to sink uses exactly one friend->report edge (since source->friend, friend->report, report->sink). So each augmenting path uses exactly one negative edge. So if we add a constant C to each friend->report edge, each path's cost increases by C. So the ordering of paths by total cost remains the same, because each path's cost is shifted by same C (since each path has exactly one such edge). Wait, is it exactly one? Yes, because the only way to go from source to sink is: source -> friend (cost 0) -> report (cost = -gain + C if we add C) -> sink (cost 0). So total cost = -gain + C. So if we add same C to all such edges, the order by original gain is preserved: lower cost (more negative) corresponds to higher gain. So after adding C, all costs become non-negative if C >= max_gain. So we can simply set cost' = C - gain, where C = max_gain (or any number >= max gain). Then all costs' are >=0. Then we run min-cost flow (where we minimize cost'). After we compute total cost', the original total cost = total cost' - C * flow (since each unit flow adds C). Since we want to maximize total gain = - (original total cost). So total gain = - (total cost' - C * flow) = C * flow - total cost'. So we can compute gain that way.
This trick eliminates need for potentials entirely! Because all edge costs become non-negative, we can use Dijkstra without potentials. And we still need to stop when the shortest path cost' (which equals C - gain) becomes >= C? Actually original gain = C - cost'. The shortest path cost' (minimum cost') corresponds to the maximum gain (since gain = C - cost'). So if the minimum cost' path has cost' = C - gain_min. We want to augment as long as gain > 0, i.e., C - cost' > 0 => cost' < C. So we can stop when the shortest distance from source to sink >= C (i.e., the best gain is non-positive). But if we set C to be something like max_gain+1, then cost' < C if gain>0; if gain=0, cost'=C; if gain<0, cost'>C. Since we only added edges with positive gain, all added edges have gain>0, so cost' = C - gain < C. So the shortest path cost' will always be < C as long as there is any edge left. However, if we run out of capacity (no path), distance will be INF, so we stop.
But we might also have edges with gain exactly 0? If gain=0, copying yields same as self. Does copying a report with zero gain affect total? It doesn't change total score, but it uses up a copy slot and friend capacity. Since we have a limit on copies L, and we may have to ensure at least K self, but copying zero gain doesn't affect total, but could be used to satisfy something? No, we only care about maximizing total, so zero gain is neutral. We could include them or not; including them might prevent us from using a positive gain later if capacities are limited. So we should not include zero gain edges because they could block better assignments. So we can just ignore zero gain edges. So all edges we add have gain>0, so cost' = C - gain, with gain>0 => cost' < C. So as long as there is an augmenting path, distance < C, and we want to augment. So we can simply run while flow < L and there is a path with finite distance (i.e., we can send flow) and the distance < C? Actually if we can send flow, distance will be < C because all edges have cost' < C (since gain>0) and source->friend and report->sink are 0 cost, so total cost' = C - gain < C. So condition holds automatically as long as there is a path. But if we eventually run out of positive gain edges (i.e., all friend->report edges are used up or capacities exhausted), then no path exists (distance INF). So we can just run while flow < L and there exists a path (distance < INF). So no need to check cost.
Thus we can transform costs to non-negative by adding a constant C to each friend->report edge. Choose C = max_gain (maximum gain among all pairs, maybe plus 1). But careful: If we set C = max_gain, then cost' = max_gain - gain, which could be 0 for the max gain edge. That's non-negative. Good. Then Dijkstra works with non-negative costs.
However, note that the costs on reverse edges (which are used for flow cancellation) will have negative of that cost? Since we add reverse edges with cost = -cost' (original cost). Actually in min-cost flow, we need to maintain costs for reverse edges as negative of forward cost, to allow cancellation. So if we set forward cost' = C - gain, then reverse cost = -(C - gain) = gain - C, which may be negative. That introduces negative costs on reverse edges. But in Dijkstra with non-negative costs, we require all reduced costs non-negative. However, if we have negative costs on reverse edges, Dijkstra may fail if those edges become active (i.e., have positive capacity). But initially reverse edges have 0 capacity. As we send flow, we may augment back along reverse edges if they get capacity. Those reverse edges could have negative cost (since forward cost' is non-negative, reverse cost is negative). This could cause negative reduced costs even if we use potentials. But we can still use potentials to keep reduced costs non-negative. However, we could avoid using potentials if we use Bellman-Ford each iteration, but that would be slow. So we still need potentials to handle negative costs on reverse edges. But maybe we can avoid using reverse edges with negative costs by not using cost transformation? Let's think.
In the standard min-cost flow algorithm, we store edges with original costs, and we use potentials to make all reduced costs non-negative, allowing Dijkstra. The transformation of adding a constant to forward edges also affects reverse edges because reverse edge cost is negative of forward edge cost. So after transformation, reverse edges have negative costs, which may become negative reduced costs even after potentials? Potentials can handle that as long as we maintain them correctly.
But if we set all forward edges to non-negative and use potentials initially computed via Bellman-Ford (or just set potentials to 0 and use Dijkstra only after ensuring all reduced costs are non-negative). Initially, reverse edges have zero capacity, so they are not considered. However, after some flow, reverse edges get capacity and may have negative reduced cost. But if we maintain potentials properly, we can keep reduced costs non-negative. So we still need potentials.
Alternatively, we could avoid using potentials if we use a "successive shortest path" algorithm that handles negative edges by using Bellman-Ford each iteration, but that might be okay if number of augmentations is small? But we have many augmentations.
But we can also use the trick of adding a constant to forward edges and also adding the same constant to the reverse edges? No, reverse edges must have opposite sign to allow cancellation.
Thus the constant trick alone doesn't eliminate need for potentials because reverse edges become negative. However, there is another trick: Since each augmenting path uses exactly one forward friend->report edge, the reverse edges that become active correspond to undoing an assignment. When we send flow back, we would be using a reverse edge that has cost = - (C - gain) = gain - C, which is negative (since gain <= max_gain, so gain - C <= 0). So reverse edges have non-positive cost (negative or zero