International Center for Picassonian Cubism is a Spanish national museum of cubist artworks, dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed in front of the facade of the museum building. The artwork is a collection of cubes that are piled up on the ground and is intended to amuse visitors, who will be curious how the shape of the collection of cubes changes when it is seen from the front and the sides.
The artwork is a collection of cubes with edges of one foot long and is built on a flat ground that is divided into a grid of one foot by one foot squares. Due to some technical reasons, cubes of the artwork must be either put on the ground, fitting into a unit square in the grid, or put on another cube in the way that the bottom face of the upper cube exactly meets the top face of the lower cube. No other way of putting cubes is possible.
You are a member of the judging committee responsible for selecting one out of a plenty of artwork proposals submitted to the competition. The decision is made primarily based on artistic quality but the cost for installing the artwork is another important factor. Your task is to investigate the installation cost for each proposal. The cost is proportional to the number of cubes, so you have to figure out the minimum number of cubes needed for installation.
Each design proposal of an artwork consists of the front view and the side view (the view seen from the right-hand side), as shown in Figure 1.
Figure 1: An example of an artwork proposal
The front view (resp., the side view) indicates the maximum heights of piles of cubes for each column line (resp., row line) of the grid.
There are several ways to install this proposal of artwork, such as the following figures.
In these figures, the dotted lines on the ground indicate the grid lines. The left figure makes use of 16 cubes, which is not optimal. That is, the artwork can be installed with a fewer number of cubes. Actually, the right one is optimal and only uses 13 cubes. Note that, a single pile of height three in the right figure plays the roles of two such piles in the left one.
Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks.
For example, consider the artwork proposal given in Figure 2.
Figure 2: Another example of artwork proposal
An optimal installation of this proposal of artwork can be achieved with 13 cubes, as shown in the following figure, which can be obtained by exchanging the rightmost two columns of the optimal installation of the artwork of Figure 1.
The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. Each dataset is formatted as follows.
w d
h1 h2 ... hw
h'1 h'2 ... h'd
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The integers w and d separated by a space are the numbers of columns and rows of the grid, respectively. You may assume 1 ≤ w ≤ 10 and 1 ≤ d ≤ 10. The integers separated by a space in the second and third lines specify the shape of the artwork. The integers hi (1 ≤ hi ≤ 20, 1 ≤ i ≤ w) in the second line give the front view, i.e., the maximum heights of cubes per each column line, ordered from left to right (seen from the front). The integers hi (1 ≤ hi ≤ 20, 1 ≤ i ≤ d) in the third line give the side view, i.e., the maximum heights of cubes per each row line, ordered from left to right (seen from the right-hand side).
Output
For each dataset, output a line containing the minimum number of cubes. The output should not contain any other extra characters.
You can assume that, for each dataset, there is at least one way to install the artwork.
We need to understand the problem fully. We have a grid w columns (x-axis) and d rows (y-axis). For each column i (1..w) we have a front view maximum height hi: the maximum number of cubes stacked in that column (i.e., the height of the tallest pile in that column). For each row j (1..d) we have a side view maximum height h'_j: the maximum number of cubes stacked in that row (i.e., the height of the tallest pile in that row). The cubes are placed on unit squares, can be stacked vertically.
We need to determine the minimum total number of cubes that can realize these front and side view constraints. There can be multiple arrangements; we can reorder columns (swap entire columns) without affecting front view? Actually front view gives heights per column line, but columns are ordered left to right. The front view is given as an ordered list from left to right. So swapping columns would change the front view ordering, which is fixed. However the problem statement says: "Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks." That means: For a given artwork (a particular arrangement of cubes on the grid), if we swap columns (i.e., permute the columns), the front view would change because the order of column heights would be permuted. However, the problem statement notes that swaps do not change the costs of building the artworks. This means that when we consider a proposal (i.e., given front view and side view), we are free to permute columns or rows to achieve a lower cube count, as long as the heights of columns as a multiset match the given front view, and similarly the rows as a multiset match the given side view. Because swapping columns doesn't change the side view; similarly swapping rows doesn't change the front view. But wait: The front view is specified per column line: if we swap columns, the front view would be different if we consider the order, but the problem might be about the actual heights of columns irrespective of order? Let's read the problem carefully.
The artwork proposal consists of the front view and the side view as shown in Figure 1. The front view indicates the maximum heights of piles of cubes for each column line (resp., row line) of the grid. So each column line (vertical line) has a maximum height. In the proposal, these heights are given in order from left to right. Similarly, side view from right-hand side gives heights per row line, from left to right? Actually "the view seen from the right-hand side" meaning you look from the right side, so you see rows (parallel to x-axis) receding away? Actually typical: front view: look from front, you see width w columns, each column height is the maximum stack height in that column. Side view: look from right side, you see depth d rows, each row height is the maximum stack height in that row.
Now, they say: "Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks." This is a hint that we are allowed to rearrange columns arbitrarily without affecting the side view (since side view only cares about rows). But the front view would change if we reorder columns, but perhaps the given front view is just a set of column heights (multiset) not necessarily fixed order? However, the input gives the front view as a sequence h1..hw (ordered). But they say swaps do not change the costs. This means that for a given proposal, we can achieve the same front and side views with different column ordering? Actually we need to interpret: The proposal defines the front view (ordered) and side view (ordered). However, we can physically arrange cubes on the ground; the columns have positions 1..w. The front view of that arrangement will be heights for each column in order. To satisfy the proposal, the front view heights (as ordered) must exactly match the given sequence. But if we swap columns, the front view ordering changes. So if we want to meet the given ordering, we cannot arbitrarily permute columns; we must place cubes so that column i has exactly hi height. However, the statement about swaps might refer to the fact that if we have a valid arrangement that meets the constraints, we can swap columns without altering the side view and still have the same total cubes, but the front view would be different; thus it might not be the same proposal. However, they say "such swaps do not change the costs of building the artworks." That suggests that when we are trying to find the minimum number of cubes, we can consider any permutation of columns that yields the same multiset? But the proposal has fixed order. But perhaps the order of column heights given in the input can be permuted because the actual arrangement can assign the column heights to columns arbitrarily? Wait: There's nuance: The front view is the maximum heights per column line. The column lines are defined by the grid columns (positions). The given front view is a list of heights for those column lines from left to right. So to satisfy the proposal, we must assign a height to each column exactly as given. So ordering matters. However, the observation that swapping columns does not change the side view might be used to argue that we can reassign which column gets which height? Actually swapping columns means moving whole column piles to different x positions. That would change the front view ordering because the heights at each x position would be swapped. So if you have a proposal, you cannot arbitrarily swap columns and still satisfy the given front view ordering unless the heights are symmetric or something.
Let's see the examples. Input: 5 5, front: 1 2 3 4 5, side: 1 2 3 4 5. Output: 15. Explanation? For a 5x5 grid, if you have heights matching both views as increasing, the minimum cubes is 15? Actually if we place cubes in a "staircase" shape: column i height = i, row j height = j, the total cubes is sum over all cells of min(column height, row height)? Possibly, the minimal total cubes is sum over i,j min(hi, vj)? Let's test: hi = 1..5, vj = 1..5, min matrix sum = 1+1+1+1+1 +1+2+2+2+2 +1+2+3+3+3 +1+2+3+4+4 +1+2+3+4+5 = sum: row1: 1+1+1+1+1=5; row2: 1+2+2+2+2=9; row3: 1+2+3+3+3=12; row4: 1+2+3+4+4=14; row5: 1+2+3+4+5=15; total=55? That's too high; output is 15. So that's not right.
Wait, maybe I misinterpret the grid size: w columns, d rows. Typically width (x) columns, depth (y) rows. Front view: heights for each column, so there are w numbers, each between 1 and 20. Side view: heights for each row, d numbers. The cubes occupy a w by d grid, each cell (i,j) can have a stack of cubes of some height h_{i,j} ≥0 integer. The constraint: For each column i, the maximum of h_{i,j} over all rows j equals the given front height hi. For each row j, the maximum of h_{i,j} over all columns i equals the given side height h'j. We need to choose nonnegative integer heights h{i,j} (the number of cubes in that cell) that satisfy these max constraints, and minimize total sum of h_{i,j}. Also cubes must be placed contiguously? No, they can be placed anywhere; the only constraints are the per-column and per-row maximums.
This is a classic problem: given row maxima and column maxima, find the minimum total sum of entries (nonnegative integers) such that for each row j, max_i a_{ij} = R_j, and for each col i, max_j a_{ij} = C_i. Actually the constraints are: max_j a_{i,j} = C_i, max_i a_{i,j} = R_j. And we want to minimize sum a_{i,j}.
But we also have the condition that each a_{i,j} is an integer (height of cube stack). The maximum constraints mean that in each column i, at least one cell must have height exactly C_i, and all cells ≤ C_i. Similarly each row j, at least one cell must have height exactly R_j, and all cells ≤ R_j.
We can choose a_{i,j} to be any integer between 0 and min(C_i, R_j) maybe, but we need to ensure that maxima are achieved exactly.
Goal: minimize total sum. This is similar to "minimize sum of matrix entries given row and column maxima" which often yields answer = sum of row maxima + sum of column maxima - sum of something? Actually think: The maximum constraints can be satisfied by putting "tall" piles only at intersections where both row and column maxima coincide? But careful.
Let's formalize: We have w columns (index i=1..w) with max heights C_i. We have d rows (index j=1..d) with max heights R_j. Define matrix H (w x d). Constraints: 0 ≤ H_{i,j} ≤ min(C_i, R_j). Additionally, for each i, there exists at least one j such that H_{i,j} = C_i. For each j, there exists at least one i such that H_{i,j} = R_j.
We want to minimize ∑{i,j} H{i,j}.
Observation: To satisfy column i's max, we need at least one cell in that column to be at height C_i. That cell also contributes to row max; if that row's max is lower than C_i, then it's impossible because H_{i,j} cannot exceed R_j. So we must have C_i ≤ R_j for that row j if we put the column's max there. Conversely, for each row's max, we need a cell where H = R_j, and that cell's column's max must be at least R_j. So feasibility requires that for each column i, there exists some row j with R_j ≥ C_i; similarly for each row j, exists column i with C_i ≥ R_j. In other words, the sets of maximum values must be compatible: The maximum among C_i must be ≤ max over R_j? Actually both must be possible to assign: In order to assign a column's max, we need to put it in a row that can accommodate that height (i.e., R_j >= C_i). However, we also need to assign each row's max to some column with C_i >= R_j. So a necessary and sufficient condition is that the multiset of values can be matched? But problem says you can assume at least one way exists.
Now, to minimize sum, we would like to put as many zeros as possible and keep the heights low, but we are forced to have some cells at the max values. For each column i, at least one cell must be C_i. For each row j, at least one cell must be R_j. We can possibly use the same cell to satisfy both a column and a row max, if we put H_{i,j} = max(C_i, R_j)? Wait, if we set H_{i,j} = C_i = R_j, then that cell satisfies both. If C_i > R_j, then setting H_{i,j} = C_i would violate row max because H_{i,j} would be > R_j. So we cannot set H_{i,j} = C_i if C_i > R_j. So the only way to satisfy column i with C_i using a cell (i,j) is if R_j >= C_i, and we set H_{i,j}=C_i. But if R_j > C_i, then setting H_{i,j}=C_i does not achieve row's max (which is R_j) because we still need some cell in that row to be R_j. Could we also use that same cell to satisfy row's max? Only if R_j = C_i. If R_j > C_i, then row j still needs a cell with value R_j; we could put that elsewhere.
Thus the problem reduces to: We have to assign to each column i a "supporting" row j where we set the height to C_i, and to each row j a "supporting" column i where we set height to R_j, with the condition that if we assign column i to row j, then we must have C_i ≤ R_j (so that setting H_{i,j}=C_i doesn't exceed row's max). Similarly, for row j assigned to column i, we need R_j ≤ C_i. So an assignment that satisfies both column and row max simultaneously (i.e., putting a "tower" that serves both) requires C_i = R_j. However, we could have a column i assigned to row j1 and row j assigned to column i2, not necessarily the same cell. But we can set multiple cells to high values. However, we can also set some cells to intermediate values to reduce sum? But the sum is minimized by making all cells as low as possible subject to constraints. Since we only need to achieve certain maxima, we can set all other cells to 0, except we may need to adjust because if we set a cell to C_i (for column i) and another cell to R_j (for row j), there is no need to have any extra cubes elsewhere. But is it always possible to set all other cells to 0? Let's test: Suppose we have column i: we set one cell (i, j_i) = C_i, where R_{j_i} >= C_i. All other cells in column i could be 0. That would satisfy column max because the max is C_i. However, we must also satisfy row max for each row j. For row j, we need at least one cell with height R_j. If we happen to have a column i' such that we set (i', j) = R_j, that's fine. Could we have rows that do not have any assigned column cell from the column assignments? Possibly, we need to set some cell in that row to R_j. So we need to pick a set of cells (i,j) that are assigned as "peak" cells: some columns may be satisfied via one cell, some rows via one cell. Ideally, we want to minimize the number of such peak cells and their heights, but we cannot avoid having at least one peak per column and one per row. However, a single cell can serve as both a column peak and a row peak if its value equals both the column max and row max. That's when C_i = R_j.
Thus the problem is similar to covering the requirements with as few tall piles as possible, and we can set all other cells to zero. But is that always feasible? Let's check with an example: w=2, d=2, C=[2,1], R=[1,2]. Can we satisfy with only two peaks? Column 1 needs a cell with height 2. That must be in a row with R_j >=2, so row2 (R=2) works. Set (1,2)=2. Column2 needs height 1, can be in any row (since both rows have R>=1). If we set (2,1)=1, then row1 max is 1 (good), row2 max from (1,2)=2 meets R2=2. So total cubes = 2+1=3. But can we do better? All other cells zero. That's feasible. So total =3. Is there any hidden constraint like the maximum must be the maximum, but if we have a cell with height 2, that's fine. So total =3 seems minimal. Check if any lower: need at least sum of column maxima? Not exactly, because one cube can serve two maxima only if equal. So lower bound: sum of column maxima + sum of row maxima - sum of overlaps from matching pairs. But that's like we want to maximize the number of times we can assign a column max and a row max to the same cell when C_i = R_j.
But consider the first example in problem: w=5,d=5, front: 1 2 3 4 5, side: 1 2 3 4 5. According to output 15. If we used the approach: set peaks on diagonal: (i,i)=i (since C_i=i, R_i=i). Then total cubes = sum_i i = 15. All other cells zero. That yields column i max = i (since only (i,i)=i, others 0 -> max = i). Row i max = i. So works. So total = 15. That matches output. Good.
Second example: 5 5, front: 2 5 4 1 3, side: 4 1 5 3 2. Output: 15. Let's test: C = [2,5,4,1,3]; R = [4,1,5,3,2]. If we set peaks on diagonal? That would give heights (2,1,5,3,2)?? Not matching. But we can pair column maxima with row maxima where they match. However, they may not be equal. We need to assign each column a cell with its height, each row a cell with its height. Since heights differ, we might need more cubes? Actually we can set a cell to a value that satisfies column i's max but also row j's max if we set it to both? But if C_i != R_j, you cannot set a single cell to both because it would need to be exactly C_i and exactly R_j. So a cell can satisfy only one of them if they are not equal, but it can satisfy both if they are equal. However, we may still set a cell to a high value that satisfies both if we set it to max(C_i,R_j) but that would exceed the other's max if it's lower. So no.
But can we set non-peak cells to nonzero values? That would increase total sum, so we avoid.
Thus the minimal sum should be sum over all columns C_i + sum over all rows R_j - sum of "matched" values where we pair a column and row with same height? But careful: If we assign a column i to a row j with C_i < R_j, we set cell (i,j)=C_i. That satisfies column i, but row j still needs a cell with value R_j. So row j's requirement is not satisfied by that cell. So we still need a separate cell for row j (unless we have another column i' with C_i' = R_j). So essentially we need to choose a set of cells that cover all column and row requirements. Each column i must have at least one cell where H = C_i. Each row j must have at least one cell where H = R_j. If a cell is used to satisfy both a column and a row, then its value must equal both, i.e., C_i = R_j. So that cell counts for both.
Thus the problem reduces to: Given bipartite graph between columns and rows where an edge (i,j) is allowed if C_i ≤ R_j? Actually to use cell (i,j) to satisfy column i, we need to set H_{i,j} = C_i, and that is allowed only if C_i ≤ R_j (since H cannot exceed row max). Similarly, to use cell (i,j) to satisfy row j, we set H = R_j, and that requires R_j ≤ C_i. So for a column i to be satisfied via row j, condition C_i ≤ R_j. For a row j to be satisfied via column i, condition R_j ≤ C_i. For a cell to satisfy both, we need C_i = R_j.
But note: We could satisfy a column i using a cell (i,j) where C_i ≤ R_j, but also we might satisfy row j using a different cell (i',j) where R_j ≤ C_i'. So it's not necessary to have the same cell.
Thus the minimal total sum is: we need to assign to each column i some height value (actually its max is fixed) and similarly rows. The total sum of all H entries is the sum of heights at the cells we set (since others are zero). But we could also set multiple cells to non-zero values? But that would only increase sum, so we keep only the "peak" cells. However, we need to ensure that if we set a cell (i,j) to C_i (to satisfy column i), then that cell also contributes to row j: its height may be less than R_j, but that's okay as long as somewhere in row j there is a cell with height R_j. So row j can have its requirement satisfied by a different cell. So we can simply pick a set of column assignments: for each column i, pick one row r(i) where we set H_{i, r(i)} = C_i, with condition C_i ≤ R_{r(i)}. And similarly for each row j, pick one column c(j) where we set H_{c(j), j} = R_j, with condition R_j ≤ C_{c(j)}. The total sum then is sum_i C_i + sum_j R_j - sum_{overlapping assignments where (i,j) is used for both column i and row j} (value, which is C_i = R_j). Because if a cell is used for both, we count it only once.
Thus we need to maximize the total overlap (i.e., number of columns and rows that can be paired with equal heights) but also considering constraints: a column i can only be paired with row j if C_i = R_j (since to serve both, heights must be equal). Moreover, if we pair them, we use that cell. But also we could pair a column i with row j even if C_i != R_j? No, cannot serve both.
Therefore, the problem reduces to: Given two multisets C and R, find the maximum sum of values of a matching between columns and rows such that matched pairs have equal values (C_i = R_j). Because each such matched pair saves that value from being counted twice (once in column sum and once in row sum). The total minimal sum would be sum(C) + sum(R) - sum_{matched pairs} value.
But is that always achievable? We need to verify that we can assign the remaining columns and rows to cells without conflict and respecting the ≤ constraints. Let's think about feasibility after we fix a matching of equal values. For each matched pair (i,j) with C_i = R_j = v, we set H_{i,j} = v. That satisfies both column i and row j. For unmatched columns i (not matched), we need to assign them to some rows, but must satisfy C_i ≤ R_j for that row. Similarly, for unmatched rows j, assign to some columns with R_j ≤ C_i. Also we must ensure that we do not assign two columns to the same row? Actually we can assign multiple columns to the same row; there is no restriction that a row can have only one "peak" cell. A row can have multiple cells with nonzero values. For an unmatched column i, we can choose any row j (including rows that are already used for a matched pair or other columns) and set H_{i,j}=C_i, provided C_i ≤ R_j. Similarly, an unmatched row j can choose any column i (including ones already used) and set H_{i,j}=R_j, provided R_j ≤ C_i. However, we must be careful: If we assign both a column i to row j (set H_{i,j}=C_i) and also assign row j to column i' (set H_{i',j}=R_j), that's fine. But can we assign two different columns to the same row? Yes, we can set multiple cells in the same row to various heights. As long as one of them achieves the row max R_j (if row j is unmatched, we need to set some cell to R_j). If row j is matched, then its max is already achieved by the matched cell. So for an unmatched row, we need to set some cell to R_j. That cell could be in a column that is matched or unmatched; but it must satisfy R_j ≤ C_i. If we use a column that already has a cell set (maybe for its own column requirement), we would be setting another cell? Actually each cell is a single (i,j). If we already set H_{i,j} to some value for column i, we cannot also set it to a different value for row j. But we could set it to a value that simultaneously satisfies both if it's equal. So if we want to assign an unmatched column i to row j, we set H_{i,j} = C_i. If row j is unmatched, we need a cell (i',j) = R_j. It could be i' = i only if C_i = R_j. But if they are not equal, we cannot use the same cell. So we need distinct cells for different assignments unless they coincide exactly in value. But we can have multiple cells in same row or column; there's no restriction on number of non-zero cells.
Thus the feasibility issue: can we always assign the remaining columns and rows to cells without conflicts such that each column i gets at least one cell with value C_i, each row j gets at least one cell with value R_j, and all cells satisfy H_{i,j} ≤ min(C_i, R_j). Moreover, we already have a set of matched cells with equal values. For unmatched columns, we need to assign each to some row (maybe the same row can host multiple unmatched columns) with condition C_i ≤ R_j. For unmatched rows, we need to assign each to some column (maybe same column hosts multiple unmatched rows) with condition R_j ≤ C_i. However, if we assign an unmatched column i to a row j, we must ensure that the cell (i,j) is not already used for a matched pair (unless that matched pair is (i,j) already, but then i would be matched). So we can pick any unused cell (i,j) that satisfies C_i ≤ R_j. Similarly for unmatched rows. Since the grid has size w x d, and w and d are up to 10, there are many cells. As long as for each unmatched column i, there exists some row j with R_j ≥ C_i, we can assign it. Similarly for each unmatched row j, there exists some column i with C_i ≥ R_j. Since the problem says at least one way exists, these conditions hold. Also, we might worry about capacity: a row j can host multiple column assignments; that's fine because the row's max is already achieved (either by a matched cell or by one of these assignments if it's exactly R_j). But if we assign an unmatched column i to row j with C_i < R_j, the row's max might still be R_j, but we need a cell with value exactly R_j somewhere. That can be done by a separate assignment for the unmatched row j to some column i' (maybe the same or different). Could there be a conflict where the only column that can host a row's max is already used to satisfy its own column max, but the cell (i,j) is already used? But we can use a different cell in same column i and same row j? No, each cell is unique. But we can use a different column for the row's max. Since there is at least one column i with C_i ≥ R_j, we can pick one that is not already used for that row? Actually we only need one cell; we can choose any column that meets the condition. So as long as there is at least one column i with C_i ≥ R_j, we can assign that row to that column. However, that column might already have an assigned cell for its own column max? That's okay, we can set another cell in that column (different row) to R_j. There's no restriction that a column can have only one non-zero cell. So capacity is not an issue. Therefore, we can always assign each unmatched column to some row (any row with R_j ≥ C_i) and each unmatched row to some column (any column with C_i ≥ R_j) independently. There's no conflict because we have w*d cells, plenty.
Thus the total minimal sum is indeed sum(C) + sum(R) - maximum total value of a matching between columns and rows with equal heights. Since each matched pair saves its value.
But wait, consider the case where there are duplicates: Suppose C = [3,3], R = [3,3]. Then sum(C)+sum(R) = 12. Maximum matching of equal values: we can match both columns with both rows? But it's a bipartite graph where edges exist if C_i = R_j = 3. The maximum matching size (in terms of number of pairs) could be up to min(w,d). But the saving per matched pair is the value (3). So maximum saving = 3 * min(w,d) maybe? But we can only match each column with one row and each row with one column, because a cell can't serve two columns or two rows simultaneously. But is it possible to have more than min(w,d) matched pairs? No. So the maximum total saved is sum of values of a maximum weight matching where each edge weight = the common value (which is same for all edges if values equal). But if multiple values, we want to maximize sum of saved values. Since each matched pair saves the value, we should match as many high values as possible.
But is it always optimal to match as many high values as possible? Intuitively yes: we want to maximize saved sum, which is sum of matched values. Since matching constraints limit number of matches, we should match the largest possible values. However, there could be interactions: matching a column with a row of equal value v uses up that column and row; but perhaps matching a column with a row of value v might prevent matching a different column and row with a higher value? But if values are equal, you want to match high values. So it's a maximum weight bipartite matching problem where weights are equal to the common value (and zero if not equal). Since w,d ≤ 10, we can solve by Hungarian or simple enumeration (since small). However, note that each column can be matched to at most one row and each row to at most one column.
But is that the minimal sum? Let's test with some examples from problem statement.
Compute: sum(C) = 1+2+3+4+5=15. sum(R) = 3+3+3+4+5=18. Total = 33. Now we look for matching equal values. C values: 1,2,3,4,5. R values: 3,3,3,4,5. Equal values: 3 (three times in R, one in C? Actually C has one 3), 4,5. So we can match: column 3 (value 3) with one of the rows with 3; column 4 (value 4) with row 4; column 5 with row 5. That's 3 matches, saved sum = 3+4+5=12. Also column 2 value 2 cannot match any row (no 2). Column 1 cannot match. So saved = 12, total = 33-12=21. That matches output.
Example 4: 3 3, C:7 7 7, R:7 7 7. sum(C)=21, sum(R)=21, total=42. Maximum matching: all three columns can match with three rows, saved = 7*3=21. So total = 42-21=21. Output is 21. Good.
Example 5: 3 3, C:4 4 4, R:4 3 4. sum(C)=12, sum(R)=11, total=23. Equal values: C has three 4's, R has two 4's and a 3. We can match at most 2 pairs with value 4 (since only two rows have 4). Saved = 4+4=8. Total = 23-8=15. Output is 15. Good.
Example 6: 4 3, C:4 2 2 4, R:4 2 1. sum(C)=4+2+2+4=12, sum(R)=4+2+1=7, total=19. Equal values: C has two 4's, one 2, another 2? Actually C: 4,2,2,4 -> values: two 4's, two 2's. R: 4,2,1 -> one 4, one 2, one 1. Maximum matching: we can match one 4 (save 4) and one 2 (save 2). Possibly also the second 4? Row only has one 4, so only one 4 match. Similarly, only one 2 match. So saved = 6, total = 13. Output is 13. Good.
Example 7: 4 4, C:2 8 8 8, R:2 3 8 3. sum(C)=2+8+8+8=26, sum(R)=2+3+8+3=16, total=42. Equal values: C has one 2, three 8's. R has one 2, one 8, two 3's. Maximum matching: match 2 with 2 (save 2), match 8 with 8 (save 8). Possibly another 8? Only one row 8. So saved =10, total = 32. Output is 32. Good.
Example 8: 10 10, all 9's. sum(C)=109=90, sum(R)=109=90, total=180. Maximum matching: all ten pairs, saved=9*10=90, total=90. Output is 90. Good.
Example 9: 10 9, C:20 1 20 20 20 20 20 18 20 20 (10 numbers), R:20 20 20 20 7 20 20 20 20 (9 numbers). Compute sum(C): 20+1+20+20+20+20+20+18+20+20 = let's add: 20*? count 20's: first, third through seventh? Actually list: 20,1,20,20,20,20,20,18,20,20. So 20 appears: positions 1,3,4,5,6,7,9,10 => that's 8 times? Let's count: 1:20, 2:1, 3:20, 4:20, 5:20, 6:20, 7:20, 8:18, 9:20, 10:20 => that's 1,3,4,5,6,7,9,10 = 8 times. 820=160, plus 1 +18 = 179? 160+1+18=179. Wait check: Actually 820=160, plus 1 =161, plus 18 =179. So sum(C)=179. sum(R): 9 numbers: 20,20,20,20,7,20,20,20,20 = eight 20's and one 7 = 820=160 +7=167. So total = 179+167=346. Now matching: we can match equal values: both have many 20's. C has 8 of 20, plus one 18, one 1. R has 8 of 20, one 7. So maximum matches: we can match up to min( number of 20 columns, number of 20 rows ) = 8 matches of value 20. Also possibly match 7? No, C doesn't have 7. Match 18? no. Match 1? no. So saved = 208 = 160. Total = 346-160 = 186. Output is 186. Good.
All examples match this formula.
Thus the solution is: For each dataset, compute sumC = sum(hi), sumR = sum(h'_i). Then find the maximum total value of a matching between columns and rows where we can match a column i with row j if hi == h'_j (i.e., equal heights). The weight of such a match is that common value. Since the graph is bipartite and values are small and sizes up to 10, we can solve maximum weight bipartite matching (Hungarian algorithm) or simpler: because weights are just the values and edges only exist when equal, we can also think of it as: For each distinct height v, we have a certain number of columns with that height (countC[v]) and rows with that height (countR[v]). In any matching, we can match at most min(countC[v], countR[v]) pairs of height v, and each such pair saves v. Moreover, matchings across different heights are independent because a column of height v cannot match a row of different height. So the maximum total saved is simply sum over all v of v * min(countC[v], countR[v]). Is that always optimal? Let's examine: Could we get a higher saved by not matching some column of height v with a row of the same height v, in order to allow matching other columns/rows of different heights? But columns of height v can only match rows of exactly the same height, because matching requires equal height to serve both with same cell. So if we don't match a column of height v, it cannot be matched at all (since it can't match a row of other height). Similarly, a row of height v can only be matched with a column of same height. Therefore, matching decisions are independent per height. So indeed the maximum saved is sum_v v * min(cntC[v], cntR[v]). This is simpler and avoids explicit bipartite matching.
But is it always true that a column of height v can only be matched with a row of exactly v? For a cell to satisfy both column's max and row's max, the cell must be set to both values, so it must be exactly equal to both. So yes, they must be equal. So the matching is constrained to pairs with equal heights. Thus the maximum number of matches for each height v is limited by the smaller count. And each such match saves v. So total saved = sum over v of v * min(cntC[v], cntR[v]).
Let's test on examples: For example 2: C=[2,5,4,1,3], R=[4,1,5,3,2]. CountC: 1:1,2:1,3:1,4:1,5:1. CountR: 1:1,2:1,3:1,4:1,5:1. min each =1 for each v=1,2,3,4,5, sum saved =1+2+3+4+5=15. sumC+sumR = (2+5+4+1+3)=15 + (4+1+5+3+2)=15 => total 30, minus 15 =15. Yes matches output.
Example 5: C=[4,4,4], R=[4,3,4]. CountC: 4:3, others 0. CountR: 4:2,3:1. min for 4 =2, saved = 4*2=8, total = (12+11)-8=15. Yes.
Example 6: C:4,2,2,4; R:4,2,1. CountC:4:2,2:2; CountR:4:1,2:1,1:1. min for 4=1, saved 4; min for 2=1, saved 2; total saved 6; sumC=12, sumR=7=19-6=13. Yes.
Example 7: C:2,8,8,8; R:2,3,8,3. CountC:2:1,8:3; CountR:2:1,3:2,8:1. min for 2=1 saved2; min for 8=1 saved8; saved=10; sumC=26, sumR=16 total42-10=32.
All consistent.
Thus the solution is straightforward: For each dataset, read w,d, then w integers (C_i), d integers (R_j). Compute sumC, sumR. Count frequencies of each height (1..20). Then saved = sum over h=1..20 of h * min(countC[h], countR[h]). Answer = sumC + sumR - saved.
One must ensure that there is at least one way. But given the problem statement, we can assume that.
But wait: Is there any scenario where the minimal sum could be less than sumC+sumR - sum_v v*min(countC,countR)? Could we do better by using cells with values lower than the maxima but still satisfy the max constraints? The total sum is sum of all entries. Our construction uses only one cell per column (for unmatched columns) and one cell per row (for unmatched rows), and matches some. That gives total sum = sumC + sumR - saved. Could there be a way to reduce sum further by not setting the unmatched column to its full max? But we must set at least one cell in that column to C_i, otherwise the column max would be less. So each column i must have at least one cell with height exactly C_i. Similarly each row j must have at least one cell with exactly R_j. So the sum of all entries is at least the sum of all column maxima plus sum of all row maxima, minus the sum of heights of cells that serve both a column and a row (since they are counted twice). In other words, a lower bound: For any set of cells that are designated as "critical" (those achieving maxima), the sum of entries is at least sumC + sumR - sum over cells that are both a column's max and a row's max of the value (since these heights are counted twice if we sum column maxima and row maxima, but in actual sum they are only once). Moreover, we cannot use a single cell to satisfy both unless the heights are equal. So the lower bound is sumC+sumR - max_{matching} sum of matched values. And we have shown we can achieve that bound by constructing a configuration that meets it exactly. So it's optimal.
Thus the answer is as described.
We should confirm with some edge cases: e.g., w=1,d=1, C=[5], R=[3]. Is this feasible? Column max 5, row max 3. To satisfy column max, we need a cell with height 5, but row max 3 would be violated because that cell height 5 > 3, not allowed. So such dataset would be infeasible. Problem says you can assume at least one way exists. So we don't need to handle infeasible.
Another edge: w=2,d=2, C=[2,2], R=[2,2]. sumC+sumR=8, saved: min counts: 2 appears twice in both, so saved = 2*2=4, answer=4. Can we construct with total 4? Yes, put 2 on diagonal and 0 elsewhere, that yields sum=4. But wait: each column needs at least one 2: column1 has (1,1)=2, column2 has (2,2)=2. Row1: (1,1)=2, row2: (2,2)=2. Sum=4. Good.
What about C=[2,2], R=[2,3]? Is feasible? Column max 2,2, row max 2,3. Need a row with 3, so need a cell with height 3. But any cell with height 3 would exceed column max (since columns max are 2). So infeasible. But not in inputs.
So algorithm: For each dataset, compute counts for columns and rows (since heights up to 20). Then compute saved = sum_{h=1}^{20} h * min(countC[h], countR[h]). Then answer = sumC+sumR - saved.
Implementation: read until "0 0". For each dataset, read w d, then next line with w ints, then next line with d ints. Note that there might be multiple lines? Input sample shows each dataset on separate lines. So we can read accordingly.
Edge: w and d up to 10, heights up to 20, so sums up to at most 1020=200 each, total 400. But final answer could be up to 1020+10*20=400, minus saved at most 200, so up to 400. However in example 9 sumC+sumR=346, answer 186. So int fine.
Thus solution is trivial.
Now, is there any twist? I've seen a known problem: "Cubist Artwork" from UVA 10177 or something? Actually I recall a problem "Cubist Artwork" (UVA 10363 maybe?) but not sure. The typical solution is exactly as we derived. However, some versions require considering both front and side views as from two directions, but there's a known nuance: The problem might also consider that the side view is from the right side, but the order of rows from left to right corresponds to increasing depth? Actually that's consistent: When looking from the right side, the rows are seen from near to far? But it doesn't matter; it's just the maximum height per row.
Thus our solution holds.
Now let's confirm with more complicated scenarios: Suppose C=[3,5], R=[5,3]. SumC+sumR=8+8=16. Counts: 3:1 col,1 row => min=1 saved=3; 5:1 col,1 row => min=1 saved=5; saved total=8, answer=8. Can we achieve total 8? Possibly set (1,2)=3 (column1, row2) because col1 max=3, row2 max=3. And (2,1)=5 (col2 max=5, row1 max=5). All others zero. Sum=3+5=8. Works.
Now consider C=[3,3,5], R=[5,3,3]. SumC=11, sumR=11, total=22. Counts: 3: col 2, row 2; 5: col 1, row 1. min for 3 =>2 saved=6; min for 5 =>1 saved=5; saved=11, answer=11. Configuration: match two 3s and one 5. Example: put 3 at (1,2) and (2,3) and 5 at (3,1). Sum=3+3+5=11. Works.
Now consider C=[2,4], R=[3,3]. Is this feasible? Column max 2 and 4, row max both 3. Need a column with 4: to place a 4, we need a row with max >=4, but rows have max 3, so impossible. So not in input.
Now consider scenario where some column heights are less than some row heights and vice versa, but there is a feasible arrangement because we can put column max in a row with higher max, and row max in a column with higher max. The feasibility condition is: For all columns i, there exists some row j such that R_j >= C_i, and for all rows j, there exists some column i such that C_i >= R_j. That is necessary and sufficient? Let's test: Suppose C=[2,3], R=[3,2]. For column 2 (C=3), exists row1 R=3 >=3. For column1 C=2, exists rows with >=2 (both). For row1 R=3, exists column2 C=3 >=3. For row2 R=2, exists column1 C=2 >=2. So feasible. Our formula works: sumC+sumR=5+5=10, counts: 2: col1, row2 => min=1 saved=2; 3: col2, row1 => min=1 saved=3; saved=5, answer=5. Achievable: put (col2,row1)=3, (col1,row2)=2. Sum=5.
Now consider C=[3,3], R=[4,2]. Feasibility? Column max 3 each. For columns, need rows with >=3: row1 R=4 qualifies, row2 R=2 does not. So each column can be assigned to row1. Row1 R=4 needs a column with >=4? No column has >=4 (max is 3). So row1's max 4 cannot be achieved because any cell in row1 can have at most min(C_i,R1) = min(3,4)=3, which is less than 4. So infeasible. So not in input.
Thus our solution is correct.
Now we need to implement reading until 0 0. But careful: Input format: w d on a line; next line contains w integers; next line contains d integers. The integers may be separated by spaces. So we can read line by line or simply use standard input reading.
Implementation in Python: while True: read line, split, if "0 0": break. Then read next line for front view: maybe read as list of ints; but if there are extra whitespace lines? Probably not. We'll use input().split().
We'll store counts in arrays of size 21 (indices 1..20). Initialize to 0.
We compute sumC, sumR, then for each hi increment countC[hi], for each hj increment countR[hj]. Then saved = sum(h * min(countC[h], countR[h]) for h in range(1,21)). answer = sumC + sumR - saved.
Print answer.
Testing with sample input yields outputs as given.
Edge: The sample includes many test cases. Works.
Thus the solution is extremely simple.
But wait, is there any possibility that we could achieve even lower sum by using cells with heights less than the maxima in some places and still satisfy max constraints, but also using multiple cells per column? Our construction uses each column exactly one cell at max, except matched ones share with rows. Could we reduce sum by not setting the column's max to a full cell? No, because we need at least one cell with that height; that cell's height is exactly the max. So it contributes that amount. So lower bound holds.
Thus final answer.
Now I'll produce the final answer.
But the problem originally may have been known as "Cubist Artwork" and typical solution is: sum front + sum side - sum over each height of height * min(count_front[height], count_side[height]).
I'll write the solution in Python.
One nuance: The input may have multiple datasets and lines could be blank? Not likely. We'll handle reading robustly: read using sys.stdin.read() and parse integers.
Let's code:
def main():
import sys
data = sys.stdin.read().strip().split()
it = iter(data)
out_lines = []
while True:
try:
w = int(next(it))
d = int(next(it))
except StopIteration:
break
if w == 0 and d == 0:
break
front = [int(next(it)) for _ in range(w)]
side = [int(next(it)) for _ in range(d)]
sumC = sum(front)
sumR = sum(side)
cntC = [0]*21
cntR = [0]*21
for h in front:
cntC[h] += 1
for h in side:
cntR[h] += 1
saved = 0
for h in range(1,21):
saved += h * min(cntC[h], cntR[h])
ans = sumC + sumR - saved
out_lines.append(str(ans))
print("\n".join(out_lines))
This should work.
But double-check that w and d can be up to 10, but heights up to 20. So fine.
Now, is there any scenario where the answer might be less than sumC+sumR - saved due to more clever overlapping? For instance, suppose we have two columns with height 5 and one row with height 5. We can only match one column with that row, saving 5. The other column must have its own cell at height 5. So sum = 5+5 (columns) + 5 (row) -5 = 10? Actually sumC=10, sumR=5, total=15, saved=5 => answer=10. Could we achieve total less than 10? Suppose we set column1's max 5 at cell (1,1) and column2's max 5 at cell (2,1) but row1 max 5 is satisfied by either; but then sum = 5+5=10, which is same. If we tried to set column2's max at a different row with lower max? Can't because must be exactly 5. So min is 10. So works.
Now consider a more complex scenario: C=[3,3], R=[3,3,3]. SumC=6, sumR=9, total=15. Counts: 3 appears 2 cols, 3 rows => min=2 saved=6, answer=9. Achievable: set (1,1)=3, (2,2)=3, and row3 needs a 3, so we can set (1,3)=3? But column1 would then have two cells: one 3 at (1,1) and another 3 at (1,3) - that's okay, column1 max still 3. Row3 gets its 3. Sum = 3+3+3 =9. Or match 2 columns with 2 rows, and then assign the third row to any column, but that adds an extra 3. So sum=9. Could we do better by using a cell that is 3 and serves both column and row for the third row and one column? But we already matched both columns; the third row must be assigned to some column, but if we assign it to a column that already has a 3, we are adding another 3 (since cell must be 3). So sum is still 9. So that's minimal.
Now consider case where some heights appear more in one side than the other, saved formula works.
Thus solution stands.
However, I recall a known problem "Cubist" from UVA 10177? Actually I've seen something like "Cubist Artwork" where the answer is sum of front and side minus sum of matched heights, but sometimes they consider that columns can be rearranged arbitrarily? Wait, in some variations, the order of columns and rows can be permuted to minimize cubes. The problem statement here says: "Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks." This indicates that we are allowed to reorder columns and rows arbitrarily when constructing the artwork. That is, we can permute the columns (the assignment of which column gets which front height) and similarly permute rows (which row gets which side height) to achieve a better matching. However, the input provides the front view as an ordered list, but we can reorder the columns because swapping columns doesn't affect the side view; but does it affect the front view? The front view is defined per column line, so swapping columns changes the front view ordering. But the proposal includes a specific ordering. However, the text says "such swaps do not change the costs of building the artworks." That might mean that if we have a particular artwork configuration, swapping columns does not alter the number of cubes needed. So when evaluating minimum cubes, we don't need to consider column order as a constraint? Actually it suggests that we are allowed to permute columns arbitrarily because it does not change the side view, and the front view would be permuted accordingly, but we can match the given front view ordering by labeling columns appropriately? Let's parse: The artwork proposal consists of the front view and the side view. The front view gives the maximum heights per column line (ordered left to right). The side view gives per row line (ordered left to right). If we physically build an artwork, we can decide which column (position) gets which height. The front view of the built artwork will be the heights of the columns from left to right. To match the proposal, this sequence must equal the given front view sequence. But if we swap columns after building, the front view changes. So we cannot arbitrarily permute columns and still satisfy the given front view, unless we consider that the proposal does not fix the order? However, the statement about swaps not affecting cost might be interpreted as: when you have an arrangement that meets the constraints, you can swap columns (which changes the front view) but the side view remains the same. So if you have a different arrangement that yields a different front view but the same side view, the cost is the same. But that doesn't directly imply we can ignore order. But many solutions to this problem (like UVA 1077? Actually I've seen a problem "Cubist Artwork" where the answer is indeed sum of heights minus sum of min counts, but they often mention that columns can be reordered because the front view only cares about the set of heights, not the order. Let's re-read problem description carefully:
"The artwork is a collection of cubes with edges of one foot long and is built on a flat ground that is divided into a grid of one foot by one foot squares. ... Each design proposal of an artwork consists of the front view and the side view (the view seen from the right-hand side), as shown in Figure 1.
The front view (resp., the side view) indicates the maximum heights of piles of cubes for each column line (resp., row line) of the grid.
There are several ways to install this proposal of artwork, such as the following figures.
Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks.
For example, consider the artwork proposal given in Figure 2. An optimal installation of this proposal of artwork can be achieved with 13 cubes, as shown in the following figure, which can be obtained by exchanging the rightmost two columns of the optimal installation of the artwork of Figure 1."
Now, Figure 1: front view heights: probably 1,2,3,4,5? Actually Figure 1 shows an example with increasing heights maybe. Then they show an optimal installation with 13 cubes. Then they say swapping columns does not change the side view, and swapping rows does not change the front view, thus such swaps do not change the costs. Then they give Figure 2: another artwork proposal (presumably different front and side) and say an optimal installation can be achieved with 13 cubes, which can be obtained by exchanging the rightmost two columns of the optimal installation of Figure 1. This suggests that the proposal in Figure 2 has a front view that is a permutation of the front view of Figure 1? Possibly Figure 2's front view is 1,2,3,5,4? Or something. So they imply that if you have an optimal arrangement for one set of front/side, by swapping columns you can get an arrangement that matches a different front view (with columns permuted) but same side view. So when computing minimum cubes, the order of columns does not matter because you can always reorder the columns to match the given front view without affecting the side view? Actually if you have a configuration that has column heights (as a multiset) matching the given front view multiset, you can permute the columns to achieve any desired order. Since swapping columns does not affect the side view, you can always rearrange the columns to match the exact ordering of the front view. Similarly, you can rearrange rows to match the ordering of the side view. Therefore, the order of heights in the input is irrelevant; only the multiset matters. So the problem reduces to: Given two multisets of heights (one of size w, one of size d), find the minimum total number of cubes needed such that there exists a w x d grid with row maxima multiset equal to the given row heights (as a multiset) and column maxima multiset equal to the given column heights (as a multiset). Because we can permute rows and columns arbitrarily.
Thus the solution we derived using matching on equal values (per height) is correct, and indeed we treated them as multisets (since we used counts). The order doesn't matter. So the minimal sum is sumC + sumR - sum_v v * min(cntC[v], cntR[v]).
Thus the solution is straightforward.
Now, let's implement and test with provided sample.
We'll also consider cases where there might be extra spaces or lines, but typical input reading will handle.
Time complexity: O(T * (w+d+20)).
Now, produce final answer.
But wait: There is a nuance: The artwork proposal includes both front and side view. But our solution uses the fact that we can rearrange columns and rows. But is it always allowed? The problem statement says: "Notice that swapping columns of cubes does not change the side view. Similarly, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks." It seems they mention it to indicate that you can rearrange without affecting the views from the other direction. So in minimizing cubes, we can assume we are free to assign which column gets which height, and which row gets which height, as long as the multiset of column heights matches the front view multiset and the multiset of row heights matches the side view multiset. Because if we find an arrangement with some assignment of heights to columns, we can always permute columns to match the exact order required. So yes.
Therefore, our solution is valid.
Now, I will write the final response.
But wait, is there any scenario where we might need to place more cubes than sumC+sumR - saved because the assignment of unmatched columns to rows might force additional cubes to avoid conflicts? For instance, if we have a column i with height 5 and we assign it to row j with R_j=6, that's fine. But if we also need to assign a row k with R_k=5 to some column, we might assign it to column i (which has C_i=5). That would require the cell (i,k) to be 5. But we already used cell (i,j) for column i's 5. That's okay, we can have two cells in column i with height 5. That would mean column i has two cells at height 5, which is fine; its max is 5. But does that increase sum? We already counted column i's max once in sumC. In our construction, we only set one cell per column (the one that gives its max). For unmatched rows, we set a cell in some column (maybe already used for its own column) to the row's max. That adds extra cubes beyond the column's max. So the total sum = sumC (each column's max appears once) + sumR (each row's max appears once) - sum of matched values (where the same cell covers both). This exactly matches our formula. So we don't need to worry about conflicts: we can always assign unmatched rows to columns that already have their max placed somewhere else; it just adds a new cell with that row's max. That adds to sum. That's accounted for in sumR. Similarly, unmatched columns add to sumC. So no extra.
Thus our construction is always feasible and yields exactly sumC+sumR - saved.
One might ask: Could we sometimes reduce sum further by using a cell that is not at the full max for a column, but still achieves column max via another cell? That is already captured: each column must have at least one cell at its max; any additional cells can be zero. So the sum cannot be lower than sumC + sumR - saved.
Therefore, the answer is as above.
Now, I'll write final code.
But wait, in example 9: We got 186. Let's double-check: sumC=179, sumR=167, total=346. Counts: C: 20:8, 18:1, 1:1; R:20:8, 7:1. min for 20=8 saved=160, min for 18=0, 1=0, 7=0, saved=160, answer=186. Yes.
Thus solution.
Now final output.
Implementation details: We'll use Python.
But the problem might be from an older contest with strict output formatting; just print each answer on its own line.
Now answer.
I'll produce final message with explanation and code. ```python
import sys
def main():
data = sys.stdin.read().strip().split()
it = iter(data)
out = []
while True:
try:
w = int(next(it))
d = int(next(it))
except StopIteration:
break
if w == 0 and d == 0:
break
code
front = [int(next(it)) for _ in range(w)]
side = [int(next(it)) for _ in range(d)]
sum_front = sum(front)
sum_side = sum(side)
cnt_front = [0] * 21 # heights are between 1 and 20
cnt_side = [0] * 21
for h in front:
cnt_front[h] += 1
for h in side:
cnt_side[h] += 1
saved = 0
for h in range(1, 21):
saved += h * min(cnt_front[h], cnt_side[h])
ans = sum_front + sum_side - saved
out.append(str(ans))
print("\n".join(out))