There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?
Input
The first line contains one integer n (2 ≤ n ≤ 5000) — the number of armchairs.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.
Output
Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.
Examples
Input
7
1 0 0 1 0 0 1
Output
3
Input
6
1 1 1 0 0 0
Output
9
Input
5
0 0 0 0 0
Output
0
Note
In the first test, you can perform the following sequence:
ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
ask a person to move from armchair 4 to armchair 5, it takes 1 minute.
In the second test, you can perform the following sequence:
ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
ask a person to move from armchair 3 to armchair 4, it takes 1 minute.
In the third test, no seat is occupied so your goal is achieved instantly.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to parse the problem carefully. The problem description: "There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.
For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.
You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?"
Interpretation: We have initial occupancy array a_i ∈ {0,1}, with number of ones ≤ n/2. We are allowed to move a person from an occupied chair to an unoccupied chair. After the move, the originally occupied chair becomes free, and the destination becomes occupied. But wait: the goal is: "every seat that was initially occupied must be free." That means at the end, for each i where a_i=1 initially, that chair must be unoccupied. The other chairs (initially empty) may be occupied or not? The description says: "You want to achieve the following situation: every seat that was initially occupied must be free." It doesn't say that initially free chairs must be occupied. They can be either occupied or free. So at the end, we don't care about occupancy of initially empty chairs; they can be occupied or empty. However, we are moving people. But there is a catch: We can only move a person from an occupied chair to an unoccupied chair. So each move reduces the number of occupied chairs? No: initially we have some occupied chairs. When we move a person from i to j, we vacate i and occupy j. So total number of occupied chairs remains constant? Actually, initially there are m = sum a_i occupied chairs. After moving, the number of occupied chairs stays m because we just relocate a person. So we will end with exactly m occupied chairs, but they must be placed on chairs that were initially free (since the initially occupied chairs must become free). That implies we need to assign each initially occupied chair to a distinct initially free chair, and move the person from the occupied chair to that free chair. But is it required that every initially free chair eventually becomes occupied? Not necessarily, because m ≤ n/2, so there are at least m empty chairs? Actually, number of empty chairs initially is n - m. Since m ≤ n/2, n - m ≥ n/2 ≥ m? Wait, n - m ≥ n/2 because m ≤ n/2 => n - m ≥ n/2. Since m ≤ n/2, we have n - m ≥ n/2 ≥ m? Not necessarily, if m < n/2 then n - m > n/2 > m. If m = n/2, then n - m = n/2 = m. So there are exactly m empty chairs if m = n/2, or more if m < n/2. So there are enough empty chairs to accommodate all persons, but we might not need to use all empty chairs; we need to place each person onto some empty chair. Since there are enough empty chairs, we can assign each person to a distinct empty chair. That's like a matching between occupied chairs and empty chairs.
But note: The moves are sequential; we can move one person at a time. The total time needed is the sum of the times of individual moves? The problem states: "You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair." So total time = sum of durations of all moves, because they happen one after another. There is no parallelization.
We can also perform multiple moves involving the same person? Possibly, we could move a person multiple times, e.g., from i to j, then later from j to k, etc. But is that beneficial? Possibly, if we need to free up an initially occupied chair, we might need to move a person out of it; but if we later move that same person again, that could be suboptimal because we could directly move them to the final target. Since moves are sequential and we sum times, it's never beneficial to move the same person more than once because we could directly move them to the final empty chair in one move, saving the intermediate steps. Unless there is some constraint like at the time of moving, the destination must be empty. If we move a person to an initially empty chair, that chair becomes occupied, but we might later want to move that person again to free up that chair? But why would we need to free up that chair? The goal is only that initially occupied chairs become free; we don't care about occupancy of initially free chairs. So we could potentially occupy an initially free chair and later move that person again to another initially free chair, but that would be wasted time. So an optimal solution will not involve moving a person more than once. However, there is also the possibility of moving a person from an initially occupied chair to a chair that is initially occupied? That's not allowed because the destination must be unoccupied at the moment of move. Initially occupied chairs are occupied, so cannot directly move to them. But after some moves, some initially occupied chairs become free because the person moved out. So it's possible that later we move a person into a chair that was initially occupied but is now free. That would be allowed because at that moment it's unoccupied. But is that beneficial? Suppose we have two initially occupied chairs A and B. We could move person from A to some empty chair E, and then move person from B to A (which is now free). This would result in A being occupied again (by person from B) but it was initially occupied, so we would not satisfy the condition that A is free at the end because B moved into it. So that's not allowed: we need every initially occupied chair to be free at the end. So after all moves, no one can be on a chair that was initially occupied. So we cannot move any person onto an initially occupied chair at any point? Actually, if we move a person onto an initially occupied chair, then at the end that chair will be occupied (unless that person later moves out). But if we later move that person out, then the chair becomes free again. So it's possible to temporarily use an initially occupied chair as an intermediate seat, as long as at the end it's free. But moving a person onto an initially occupied chair temporarily might enable some efficient routing? However, since moves are sequential and we sum distances, using intermediate chairs that are not the final destination might increase total distance compared to direct moves. But there might be a scenario where direct moves are not possible because the target empty chair is currently occupied? Let's think: we have a set of initially occupied chairs I (size m) and initially empty chairs E (size ≥ m). We need to assign each person in I to a distinct final chair in some subset of E (size m), and move them. The moves can be done in any order. While moving, we must ensure that the destination is unoccupied at that moment. Since we are moving each person exactly once directly to its final chair, we must ensure that the final chair is empty when we make the move. Initially, all chairs in E are empty. But if we move a person to a chair e in E, then e becomes occupied. If later we need to move another person to that same e, it's not allowed because e is already occupied. So we need to assign distinct final chairs to each person. So we need a matching between I and a subset of E. If we do direct moves in some order, we must ensure that at the time we move a person, its target chair is empty. Since all targets are distinct and initially empty, we could simply move persons to their assigned target chairs in any order; as long as no two persons are assigned the same target, the target will be empty at the time of move because we haven't occupied it yet (unless we move someone else to it earlier). But if we move one person to a chair that is also the target for another person, that would cause conflict. So as long as assignments are distinct, we can sequence moves such that when we move a person to its target, that target hasn't been occupied by a previous move. So direct moves with distinct final chairs are feasible.
But could there be a scenario where moving a person multiple times reduces total distance? For example, maybe by moving a person from an occupied chair to an initially occupied chair that later becomes free, and then moving that person again to a final empty chair, could the sum of distances be less than directly moving from initial to final? Because the direct distance might be large, but moving to an intermediate location that is "on the way" for two persons might allow a different assignment? However, moving a person twice will add extra distance. For any two-step move: from i to k then to j: distance = |i - k| + |k - j|. By triangle inequality, that is at least |i - j|, with equality only if k lies between i and j. So moving via an intermediate location is at least as long as direct move, and strictly longer if k is not on the direct path. But could it allow a better overall assignment because we can use chairs as temporary spots to free up other chairs? Since the final assignment must be a bijection between I and some m of E, the sum of distances for direct moves is sum_{matching} |i - f(i)|. That's a classic assignment problem: we have positions of occupied chairs and positions of empty chairs, we need to match each occupied to a distinct empty, minimizing total absolute differences. That seems plausible: the minimum total distance to move each person to a distinct empty chair, with moves executed sequentially, but the sum of distances is independent of order. However, is there any twist due to sequential nature? Could the order affect the total time because chairs become occupied/unoccupied in between? If we do direct moves, as argued, we can pick an order that avoids conflicts. The total time is the sum of the individual move durations because they are sequential. So if we have a matching, the total time is sum of distances. That would be the answer if it's optimal.
But let's test with examples: First example: n=7, a = [1,0,0,1,0,0,1]. So occupied at positions 1,4,7. Empty at 2,3,5,6. m=3. To minimize sum of distances, we need to assign each occupied to a distinct empty. We want to minimize total |i - j|. The optimal matching: 1->2 (dist 1), 4->5 (dist 1), 7->6 (dist 1) total 3. That matches output 3. So seems to be the assignment problem.
Second example: n=6, a = [1,1,1,0,0,0]. Occupied: 1,2,3. Empty: 4,5,6. Minimizing sum of |i - j|: we can match 1->4 (3), 2->5 (3), 3->6 (3) total 9. But output is 9? Wait output in example is 9. Yes, output is 9. That matches.
Third example: all zeros, m=0, total=0.
So far it seems to be classic assignment: we need to move each person from an occupied position to a distinct empty position, minimizing sum of distances.
But why the condition that m ≤ n/2? That suggests we have enough empty chairs. The classic problem of minimum sum of distances when matching two sets of points on a line: the optimal matching is to sort occupied positions and empty positions and match them in order (by greedy). That works regardless of sizes, but requires that the number of empty chairs is at least m. Since m ≤ n/2, that's guaranteed. So the solution is to compute the minimum total distance by matching the sorted lists.
But wait: is there any nuance about sequential moves that could reduce total time below that sum? For instance, suppose two persons are close to each other and there are empty chairs near them but not enough. Could we move one person to an initially occupied chair that is between them, then move the other to that person's original chair, etc., to achieve a lower sum? Actually, that would be like swapping people, but the constraint that the destination must be empty at the time of move means we might need to temporarily vacate a chair. But swapping two persons directly would require moving one to a temporary empty chair, then moving the other into the first's chair, then moving the first from the temporary to the second's chair. That's three moves, total distance maybe larger. But if we are matching I to E, we don't need to swap; we just assign each to an empty.
But consider an example: n=4, a = [1,1,0,0]. Occupied: 1,2; empty:3,4. Greedy matching: 1->3 (2), 2->4 (2) total=4. Is there a way to achieve total time less than 4? What if we move person at 2 to 3 (dist 1), then person at 1 to 2 (dist 1) — but 2 is initially occupied, but after first move, chair 2 becomes free? Wait after moving person from 2 to 3, chair 2 becomes free. Then we can move person from 1 to 2 (dist 1). At the end: chair 1 is free (since person left), chair 2 is occupied (by person from 1), chair 3 occupied (by person from 2), chair 4 empty. But the goal: every seat that was initially occupied must be free. Initially occupied: chairs 1 and 2. At the end, chair 2 is occupied (by person from 1), so condition is not satisfied because chair 2 is initially occupied and now occupied. So that doesn't meet goal.
What if we move person from 1 to 3 (dist 2), then person from 2 to 4 (dist 2) total=4. That works. Or move person from 1 to 4 (3), person from 2 to 3 (1) total=4. So 4 seems minimal.
What about scenario where there is an empty chair between them: n=5, a = [1,0,1,0,0]. Occupied: 1,3; empty:2,4,5. Greedy matching sorted: occ [1,3], empty [2,4,5]; match 1->2 (1), 3->4 (1) total=2. Could we do better? 1->2 (1) and 3->2? can't because 2 already occupied. 1->4 (3) and 3->2 (1) total=4. So 2 is minimal.
Now consider a more complex case: occupied and empty interleaved: n=6, a=[1,0,1,0,1,0]. Occupied:1,3,5; empty:2,4,6. Greedy: 1->2 (1),3->4(1),5->6(1) total=3. Could we do 1->4(3),3->2(1),5->6(1) total=5. So 3 minimal.
It seems straightforward.
But is there a scenario where moving a person multiple times could lead to less total time than direct matching? Since distances are positive and triangle inequality ensures that direct is never longer, but maybe using multiple moves allows a different final assignment that has lower total sum? For example, suppose we have two occupied chairs and two empty chairs, but the empty chairs are not both on the right; maybe the optimal direct matching sum is large, but by using a chain of moves we could effectively "swap" the persons' final positions without moving them far? Wait the final assignment is a matching between I and some subset of E. The total sum of distances for direct moves equals sum|i - f(i)|. That's a combinatorial optimization. Could there be a scenario where we could achieve the goal (all initially occupied free) with total time less than the minimum possible sum of direct distances? Let's examine: we have to end with each person in some chair that is initially empty (since initially occupied chairs must be free, so persons cannot end there). So each person ends up at some chair in E. Thus the final configuration is a mapping from I to a subset of E (bijection). The total movement time is the sum of distances each person traveled. But if we allow multiple moves per person, the total distance each person travels is at least the distance between start and final position (by triangle inequality). So total sum of distances across persons is at least sum |i - f(i)|. And if each person moves exactly once, total = sum|i - f(i)|. So the minimal total time is exactly the minimum possible sum|i - f(i)| over matchings. So the problem reduces to that.
But wait, is it always possible to achieve the configuration with each person moving exactly once directly to final target, without conflicts, such that total time is sum of distances? As argued, we can order moves arbitrarily: just move each person to their final target. Since the final targets are distinct, and initially empty, we just need to ensure we don't move a person to a target that will later be needed by another person. But if we move a person to a target that is also the final target of another person, then that other person's target becomes occupied, and they cannot move there. So we must avoid that. But if the final targets are distinct, we can schedule the moves in any order: for each target, it is empty initially and will only become occupied when we move a person onto it; after that, we never need it again. So we can, for instance, process the persons in any order, moving each to its target, and as long as the target hasn't been used before, it's empty. So it's feasible.
Thus the answer is indeed the minimum sum of absolute differences between occupied and empty positions when matched one-to-one.
Now we need to compute that efficiently given n ≤ 5000. m ≤ n/2 ≤ 2500. So m up to 2500. The classic approach: sort list of occupied positions (size m) and empty positions (size p = n - m, p >= m). Then dynamic programming: dp[i][j] = minimal total distance using first i occupied (i from 0..m) and first j empty (j from 0..p). Transition: either we do not match the j-th empty to the i-th occupied? Actually, we need to match each occupied to a distinct empty. Standard DP: dp[i][j] = minimum total cost to match the first i occupied chairs with some j of the first j empty chairs (with j >= i). Transition: either we match i-th occupied with j-th empty: dp[i-1][j-1] + |occ[i] - empty[j]|, or we skip this empty: dp[i][j-1] (i.e., we don't use empty j for any occupied). So DP complexity O(m * p) ≤ O(m * n) ≤ 2500*5000=12.5 million, which is okay. Also we can use DP with reduced memory.
Alternatively, we can note that in a line, the optimal matching is to match in order, but only if m = p? Actually, if m = p (equal number of occupied and empty), the greedy matching (i-th occupied to i-th empty) is optimal by a simple exchange argument. But here p >= m, and the optimal is to match each occupied to a distinct empty, but not necessarily the first m empties? Actually, if we sort both lists, the optimal matching is to pair the i-th occupied with the i-th empty in the sorted order, but with the condition that we can skip empties. There is a known result: given two sets of points on a line, the minimum total distance matching (where each point in the smaller set is matched to a distinct point in the larger set) is achieved by matching in sorted order, i.e., the i-th smallest occupied matches to the i-th smallest empty? That is not always true if the number of empty is larger. For example, occupied: [1, 100], empty: [2, 3, 99]. Sorted: occ:1,100; empty:2,3,99. If we match in order: 1->2 (1), 100->3 (97) total=98. But maybe better: 1->2 (1), 100->99 (1) total=2? Actually 100->99 distance=1, but then empty 3 unused. Total=2. That matches occ1->2, occ2->99, which is not strictly the i-th empty in order because empty list sorted is [2,3,99]; we used empty[1]=2 and empty[3]=99, skipping empty[2]=3. That's still matching in sorted order? If we consider we need to choose a subsequence of empties of length m that minimizes sum|occ_i - emp_{k_i}| with k_i increasing. That is exactly the DP: we choose a matching that preserves order. By the rearrangement inequality, the optimal matching between two sorted sequences when one can skip elements from the longer list is to match in order but skip some empties such that each occupied is matched to an empty that is "closest" in order. This can be solved by DP as described. So greedy in-order matching (i-th occupied to i-th empty) would be suboptimal if there are closer empties later for later occupied. So DP is necessary.
But note: Since m ≤ n/2, p ≥ m, but DP O(m * p) is fine.
However, we must check constraints: n up to 5000, m up to 2500. O(m * p) up to 25002500? Actually p can be as large as 5000, but m ≤ p, so worst-case m = 2500, p = 5000 - 2500 = 2500? Wait if n=5000, max m is floor(5000/2)=2500. So p = n - m, at least 2500. The maximum p is when m=0, but then dp trivial. In worst-case m = 2500, p = 2500. So product = 6.25e6. That's fine. But could m be less than 2500, p larger? For example n=5000, m=1, p=4999, DP would be 14999 = trivial. So overall fine.
Thus solution: read n, read array. Extract indices (1-based) of ones (occupied) and zeros (empty). Let occ[] of length m, empty[] of length p. DP: dp[j] maybe after dimension reduction: for i from 1..m, we fill dp[i][j] for j from i..p (since need at least i empties). Use rolling array: dp_prev[j] for i-1, and compute dp_cur[j] for i. For each i, for j from i to p: dp_cur[j] = min(dp_cur[j-1], dp_prev[j-1] + |occ[i] - empty[j]|). Initialize: dp[0][j] = 0 for all j >=0 (matching 0 occupied costs 0). And dp[i][i-1] = INF (not enough empties). So we can implement.
Alternatively, use full DP table with long long.
But caution: distances can be up to n (5000), sum can be up to mn which is ≤ 25005000 = 12.5e6, fits in int, but better use long long for safety.
We'll compute dp[i][j] as minimal cost to match first i occupied with some j empties (using first j empties). Transition: dp[i][j] = min(dp[i][j-1], dp[i-1][j-1] + |occ[i]-empty[j]|). For i=0: dp[0][j]=0 for all j. For j < i: dp[i][j] = INF.
Finally answer = dp[m][p] (using all empties? Actually we need to match all i=m, and we can use any j from m to p, but dp[m][p] is minimum cost using first p empties (all empties) to match all m. Since we can skip empties at the end, dp[m][p] will consider skipping them too. So answer is dp[m][p].
Double-check with examples: Example1 occ=[1,4,7], empty=[2,3,5,6]. m=3, p=4. DP:
Initialize dp[0][j]=0.
i=1:
j=1: dp[1][1] = min(dp[1][0]=INF, dp[0][0]=0? Actually dp[0][0] is 0? we need dp[0][j] for j>=0. Typically we set dp[0][0]=0, dp[0][j]=0 for j>=0? But careful: dp[0][j] means matching 0 occupied using first j empties, cost 0. So dp[0][0]=0, dp[0][1]=0,... So dp[0][0]=0. For j=1: dp[1][1] = min(dp[1][0]=INF, dp[0][0] + |1-2|=1) => 1.
j=2: dp[1][2] = min(dp[1][1]=1, dp[0][1]+|1-3|=2) => 1.
j=3: dp[1][3] = min(dp[1][2]=1, dp[0][2]+|1-5|=4) => 1.
j=4: dp[1][4] = min(dp[1][3]=1, dp[0][3]+|1-6|=5) => 1.
But could there be any subtlety? Let's read the problem statement carefully: "You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair." So total time = sum of durations. So answer is sum of distances. The matching interpretation seems correct.
One nuance: The number of occupied chairs is at most n/2. This ensures that there are at least as many empty chairs as occupied ones (since if m = n/2, then n - m = n/2, which equals m; if m < n/2, then n - m > m). So we can always find distinct empty chairs for everyone. Good.
Therefore the problem reduces to: given positions of ones and zeros on a line, find minimum total distance to assign each one to a distinct zero.
We need to implement efficiently.
DP approach: we have two lists: A (ones indices) and B (zeros indices). Let m = len(A), p = len(B). We'll use 0-indexed for DP convenience.
Let dp[i][j] be min cost to match first i ones (i from 0..m) using first j zeros (j from 0..p). dp[0][j] = 0. For i>0, dp[i][j] = INF if j < i. For j >= i: dp[i][j] = min(dp[i][j-1], dp[i-1][j-1] + |A[i-1] - B[j-1]|). We'll use rolling array.
Implementation steps:
Read n.
Read array a.
Create vector ones, zeros.
Loop i from 1..n (1-indexed) and if a_i == 1 push i to ones; else push i to zeros.
m = ones.size(); p = zeros.size().
If m == 0: print 0 and return.
Initialize prev_dp of size p+1, with zeros: prev_dp[j] = 0 for all j from 0..p.
For i from 1 to m:
cur_dp = vector(p+1, INF).
// For j from 0 to i-1, cur_dp[j] = INF (but we can start j from i)
for j from i to p:
// dp[i][j] = min(dp[i][j-1], dp[i-1][j-1] + dist)
// We need to ensure dp[i][j-1] is computed (which is cur_dp[j-1]) because we are iterating j increasing.
long long direct = prev_dp[j-1] + abs(ones[i-1] - zeros[j-1]);
long long skip = (j-1 >= i) ? cur_dp[j-1] : INF; // but j-1 might be < i, then dp[i][j-1] is INF. However dp[i][j-1] would be INF if j-1 < i. So we can compute conditionally.
// Simpler: set cur_dp[j] = direct; then if j > i, cur_dp[j] = min(cur_dp[j], cur_dp[j-1]).
cur_dp[j] = direct;
if (j > i) cur_dp[j] = min(cur_dp[j], cur_dp[j-1]);
// after loop, set prev_dp = cur_dp.
Answer = prev_dp[p].
Edge Cases: m=0 -> 0.
Complexities: O(m * p) time, O(p) space.
But careful: In the inner loop, we need to handle the case where j=i: direct = prev_dp[i-1] + dist, and skip can't be used because dp[i][i-1] is INF. So we do direct; then for j>i we also compare with cur_dp[j-1] (which is dp[i][j-1] already computed). That's correct.
Initialize prev_dp: for j from 0..p: prev_dp[j] = 0. That's dp[0][j] = 0.
Now test with the examples and maybe some random cases.
But before finalizing, let's double-check the problem statement for any twist that might invalidate this interpretation. The phrase: "you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. ... You want to achieve the following situation: every seat that was initially occupied must be free." This indeed implies that after all moves, each initially occupied seat has no one sitting there. That means all persons originally on those seats must have moved elsewhere. They could end up on initially empty seats. So yes.
But could there be a possibility that some initially empty seat is occupied by more than one person after moves? No, because each move moves a single person to an empty seat. After a move, the destination becomes occupied, and the source becomes empty. So at any time, there is still exactly one person per occupied seat; no two persons share a seat. So final configuration also has exactly m occupied seats, all of which are initially empty. So it's a perfect matching.
Thus the solution stands.
Now we need to output the minimum total time.
Double-check constraints: n up to 5000, so DP O(n^2/4) ~ 6.25 million, which is fine in C++.
But we need to ensure we handle 1-indexed positions and abs differences.
Now what about alternative solution using greedy with dynamic programming? This is essentially a minimum-cost matching on a line which can be solved with DP as we did. So we are good.
I'll write code accordingly.
But wait: there might be a nuance: The operations are sequential, and we can move a person from an occupied chair to an unoccupied one. But note that during the sequence, the set of occupied chairs changes, and we could potentially move a person from a chair that was initially empty but now occupied. That is, we could move the same person multiple times. But as argued, it can't reduce total cost.
However, consider a scenario: two occupied chairs close together, and one empty chair far right. For m=2, p=2? Actually if p>m, maybe we could move a person to an empty chair, then later move that person again to a different empty chair to free up something? But does that help reduce total sum? Let's examine an edge case:
Suppose occ: [2,3], empty: [1,100]. m=2, p=2. Direct matching: we could match 2->1 (1), 3->100 (97) total 98. Or match 2->100 (98), 3->1 (2) total 100. So minimal 98. Could we do better by using multiple moves? For instance, move person from 2 to 1 (1). Now chairs: occupied: 1 (by person originally from 2) and 3 (original). Now we need to free chairs 2 and 3? Actually initially occupied are 2 and 3. After first move, chair 2 is empty, chair 3 occupied. So we need to free chair 3. But chair 1 is occupied but was initially empty. That's okay. Now we need to move the person from 3 to some empty chair that is initially empty? The empty chairs: originally empty were 1 and 100, but 1 is now occupied. So currently empty chairs: 2 (since we vacated) and 100 (still empty). But chair 2 is initially occupied (but now empty). It is allowed to move to chair 2? But at the end, chair 2 must be free (initially occupied). If we move the person from 3 to chair 2, then chair 2 becomes occupied, which violates goal because it was initially occupied. So we cannot end with someone on chair 2. So moving to chair 2 is not allowed unless we later move that person out. So maybe: move person from 2 to 1 (1). Then move person from 3 to 100 (97) -> total 98, same as direct.
What if we try: move person from 3 to 2 (1) -> but 2 is occupied initially? Actually at start, 2 is occupied by a person. So we cannot move to 2 because it's occupied. So we need to free 2 first. Move person from 2 to 1 (1). Now 2 empty. Then move person from 3 to 2 (1). Then we have persons at 1 and 2; but chair 2 is initially occupied, so at end it's occupied, violation. So we need to move the person now at 2 to some other empty, maybe 100. So move person from 2 to 100 (98). That sequence: move 2->1 (1), move 3->2 (1), move 2->100 (98) total 100. Worse.
Maybe move 2->100 (98), then move 3->1 (2) total 100. Not better.
Could we use the fact that after moving 2->1, we have an empty chair 2 that we could use as temporary for 3, but then need to move 3 again? That seems longer.
So direct matching seems optimal.
Another potential nuance: The sequential constraint might allow overlapping? But it's sequential, not parallel, so no.
Thus DP is correct.
Now implement.
But we should consider if there's any scenario where it's beneficial to move a person from an occupied chair to another occupied chair after that chair becomes empty? That would mean the destination is initially occupied but after moving the first person out it becomes empty. Could that lead to a better sum? Let's test a case: occ: [1,10], empty: [5,6]. m=2, p=2. Direct matching: 1->5 (4), 10->6 (4) total=8. Alternative: move person from 1 to 5 (4). Now chairs: occupied 5 (orig1) and 10; empty: 1,6. Then move person from 10 to 1 (9). But 1 was initially occupied, so at end, chair 1 is occupied -> violation. So not allowed. Could move person from 10 to 6 (4) after? That's the same. Or: move 1->6 (5), then 10->5 (5) total 10. Not better.
What about occ: [1,2,6], empty: [3,4,5] (p=3,m=3). Direct matching sorted: occ:1,2,6; empty:3,4,5. Greedy matching: maybe 1->3 (2), 2->4 (2), 6->5 (1) total=5. Could we do better via intermediate? For instance, move 2->3 (1), then 1->2 (1), then 6->5 (1) ??? But after first: 2->3, chair2 empty; second: 1->2 (1) -> now chairs: 1 empty, 2 occupied (by 1), 3 occupied (by 2), 5 empty, 6 occupied. But chair 1 is initially occupied and is empty, good; chair 2 initially occupied and now occupied (by 1) -> violation. So not allowed. Maybe: move 6->5 (1), then 2->6? but 6 becomes empty after? Actually after first: 6->5, chair6 empty; then 2->6 (4) -> chair2 empty, chair6 occupied by 2. Chair6 initially occupied? Actually 6 was initially occupied, but now occupied by 2, violation. So not.
Thus direct matching seems optimal.
But what about scenario with more empties than occupied, like occ: [5], empty: [1,100]. m=1, p=2. Direct matching: min distance = min(|5-1|=4, |5-100|=95) =4. So answer 4. Could we do something like move 5->1 (4) then 1->100? That would be extra, not needed. So answer 4.
So DP is correct.
Now think about other interpretations: Could the goal be to free all initially occupied chairs, but the people can end up anywhere, even multiple on same chair? The problem says "at most one person per armchair" is initially true, and after moves, since we only move one person to an empty chair, that property holds. So no stacking.
Thus solution is DP.
Now check constraints: n up to 5000, but we should consider using int for dp? Distances up to 5000, max sum if m=2500 and each distance up to 5000 => 12.5e6, fits in 32-bit signed int (2^31-1 = 2.147e9). So int is fine. But we may use long long for safety.
Implementation details:
Read n.
Vector a(n)
Loop i=0..n-1, read a[i]. If a[i]==1, push i+1 to ones; else push i+1 to zeros.
m = ones.size(); p = zeros.size().
if m == 0: cout << 0 << endl; return.
Use vector dp_prev(p+1, 0).
For i=1..m:
vector dp_cur(p+1, INF). // we can set INF as something like LLONG_MAX/2.
For j=i; j<=p; ++j:
long long cost = dp_prev[j-1] + abs(ones[i-1] - zeros[j-1]);
dp_cur[j] = cost;
if (j > i) dp_cur[j] = min(dp_cur[j], dp_cur[j-1]);
dp_prev = dp_cur.
cout << dp_prev[p] << endl.
Testing with examples.
But we need to be careful: dp_prev has length p+1, and we use index j-1, okay.
Now, verify with a random case using brute force for small n to ensure DP correct.
Let's do mental test: n=3, a=[1,0,1]? m=2, p=1, but m <= n/2? n/2=1.5 floor maybe? Actually condition: number of occupied armchairs is not greater than n/2. For n=3, n/2=1.5, so occupied <=1.5 -> at most 1. So a=[1,0,1] is invalid because m=2 > 1. So problem ensures m ≤ floor(n/2). So p ≥ m. So we always have p >= m. Good.
Now, test with n=4, a=[1,0,0,1] (m=2, p=2). occ=[1,4], empty=[2,3]. DP:
prev: [0,0,0]
i=1:
j=1: cost = dp_prev[0]+|1-2|=0+1=1; dp_cur[1]=1; (j>i? no) =>1
j=2: cost = dp_prev[1]+|1-3|=0+2=2; dp_cur[2]=2; j>1? yes => min(2, dp_cur[1]=1) =>1
dp_prev now [?,?] Actually dp_prev becomes dp_cur, but we need to represent only indices from 0 to p. However our dp_cur only computed for j>=i. For j < i we leave INF? But we don't need them because future i only uses j>=i. But careful: In next iteration, dp_prev should have dp_prev[j] for j from 0..p. For j less than i-1? Actually when we move to i+1, we will need dp_prev[j-1] for j-1 >= i. So dp_prev must be defined for indices from 0..p. We set dp_cur with default INF, but we don't need dp_cur[0..i-1] for future? In next iteration, when i=2, we will compute dp_cur[2] using dp_prev[1] (which is dp for i-1=1 at j=1). So dp_prev[1] must be correctly set from previous iteration. In our code, we set dp_cur with size p+1, default INF. Then we fill j from i to p. For j < i, we leave INF. But after iteration, we assign dp_prev = dp_cur. Then for the next i (i+1), we will need dp_prev[j] for j from i (since we need dp_prev[j-1] for j >= i+1). So we need dp_prev at index i to be defined (maybe INF). But j=i, we need dp_prev[i-1] which is dp_prev at index i-1. So we need dp_prev[i-1] to be defined correctly. That is from previous iteration we set dp_cur[i-1]? Actually at iteration i, we computed dp_cur for j from i to p. For j=i-1, we left it as INF. But dp_prev for index i-1 is needed in next iteration? For next i' = i+1, we will compute for j' = i+1..p. For j' = i+1, we need dp_prev[j'-1] = dp_prev[i]. That's dp_cur[i] which we computed. For j' = i+2, need dp_prev[i+1] which is dp_cur[i+1] computed. So the indices we need are >= i. So dp_prev[i-1] is not needed. So leaving dp_cur[0..i-1] as INF is okay. However, we must be careful that dp_prev[j] for j < i-1 is not needed. So our approach works. But to be safe, we could explicitly set dp_cur[0..i-1] = INF. However, we don't access them later. So fine.
Now test with n=4, a=[1,0,0,1] with our algorithm:
Initialize prev = [0,0,0,0] (p=2? Actually p=2, so prev size 3 (index 0..2) or p+1=3). Wait p=2, so indices 0,1,2. So prev = [0,0,0].
i=1 (first occupied):
for j=1..2:
j=1: cost = prev[0] + |1-2|=0+1=1; dp_cur[1]=1; if j>1? no.
j=2: cost = prev[1] + |1-3|=0+2=2; dp_cur[2]=2; j>1: min(2, dp_cur[1]=1) -> 1.
Also dp_cur[0] remains INF (but we didn't set it, we can initialize all to INF). But we need to ensure prev after assignment is dp_cur, which will have INF at index 0. That's okay for next iteration, because we won't use prev[0] for i=2? For i=2, j will start at 2, we need prev[1] (j-1=1). prev[1] is 1 (ok). So dp_cur[0] INF not used. So after i=1, prev = dp_cur = [INF, 1, 1] (since dp_cur[2]=1). Actually dp_cur[2] became 1. So prev[1]=1, prev[2]=1.
i=2:
for j=2..2:
j=2: cost = prev[1] + |4-3| = 1+1=2; dp_cur[2] = 2; j>2? no.
So dp_cur[2]=2. dp_cur[0] and dp_cur[1] are INF. Then answer = prev[p] = prev[2] = 2. That is total distance: 1->2 (1), 4->3 (1) total 2. That matches expectation? Check: occ:1 and 4, empty:2,3. Minimum sum: either 1->2 (1) 4->3 (1) sum=2; or 1->3 (2) 4->2 (2) sum=4. So answer 2. Good.
Now test with n=5, a=[1,0,1,0,0] occ=[1,3] empty=[2,4,5]. m=2, p=3. DP:
prev: [0,0,0,0]
i=1:
j=1: cost=0+|1-2|=1 -> dp_cur[1]=1
j=2: cost=0+|1-4|=3 -> dp_cur[2]=3; j>1 => min(3,1)=1
j=3: cost=0+|1-5|=4 -> dp_cur[3]=4; min(4,1)=1? Actually j>1, compare with dp_cur[2] which is 1, so min(4,1)=1.
So prev becomes [INF,1,1,1] (index0 INF).
i=2:
j=2: cost=prev[1]+|3-4|=1+1=2 -> dp_cur[2]=2
j=3: cost=prev[2]+|3-5|=1+2=3 -> dp_cur[3]=3; j>2 => min(3, dp_cur[2]=2) =2
So answer prev[3]=2. That matches earlier: 1->2 (1), 3->4 (1) total 2. Good.
Now test with the earlier example that required skipping an empty: occ=[1,100], empty=[2,3,99]. m=2, p=3. DP:
prev: [0,0,0,0]
i=1:
j=1: cost=0+|1-2|=1 -> dp_cur[1]=1
j=2: cost=0+|1-3|=2 -> dp_cur[2]=2; min(2,1)=1
j=3: cost=0+|1-99|=98 -> dp_cur[3]=98; min(98,1)=1
So prev = [INF,1,1,1]
i=2:
j=2: cost=prev[1]+|100-3|=1+97=98 -> dp_cur[2]=98
j=3: cost=prev[2]+|100-99|=1+1=2 -> dp_cur[3]=2; min(2, dp_cur[2]=98) = 2
Answer=2. Good.
Thus DP works.
Now we need to be careful with INF: set as something like 1e18.
Edge Cases: m = 0: answer 0.
Complexity O(m * p) ≤ 6.25e6, fine.
Now we should also consider a potential nuance: the problem says "the number of occupied armchairs is not greater than n/2". So m ≤ floor(n/2). That's already used.
Now let's double-check the second example: they provided a sequence of moves that sum to 9, but note that they moved person from armchair 4 to armchair 5, then later moved person from armchair 3 to armchair 4. That involves moving a person (from 4) to 5, then later moving another person onto 4 (which was initially occupied). That is allowed because after the first move, chair 4 becomes free (since originally occupied by person from 4? Actually initially occupied chairs: 1,2,3. They moved 1->4 (3 min), then 2->6 (4 min), then 4->5 (1 min) — wait they moved person from 4? But 4 was initially empty, but after first move (1->4), chair 4 becomes occupied by person from 1. Then they moved that person from 4 to 5 (1 min). Then moved person from 3 to 4 (1 min). So they used a chair that was initially empty (4) as an intermediate for person from 1, and then later used it as final destination for person from 3? Actually final destinations: person from 1 ends at 5, person from 2 ends at 6, person from 3 ends at 4. All final chairs (4,5,6) are initially empty. So they matched 1->5, 2->6, 3->4, with distances 4,4,1? Wait 1->5 = 4, 2->6 = 4, 3->4 = 1 total 9. But the direct matching that gave total 9 would be 1->4 (3), 2->5 (3), 3->6 (3) total 9. Alternatively, 1->5 (4),2->6 (4),3->4 (1) total 9. Both sum to 9. So there are multiple optimal matchings. Their sequence used an intermediate move (1->4 then 4->5) which increased distance for person 1: 1->4 (3) + 4->5 (1) = 4, which is the same as direct 1->5 (4). So they effectively used two moves for person 1, but total distance sum same as direct. So multi-move doesn't reduce total.
Thus all good.
Now we can code.
But hold on: The DP solution we derived assumes we can directly match each occupied to an empty, but is it always possible to schedule moves such that total time equals sum of distances without extra waiting or something? Since moves are sequential, we might need to consider that while one person is moving, others are stationary, but that doesn't affect total time because the next move starts after previous finishes. So total = sum.
Thus answer is minimum sum of distances.
Therefore we can implement.
But before finalizing, let's check for any other interpretation: Possibly the goal is to make every initially occupied chair free, but we could also have some persons end up in chairs that were initially occupied but have been vacated? No, that would violate condition. So no.
Thus the problem is a classic DP.
Now I'll write solution.
But wait: Could there be a scenario where we need to move a person from an occupied chair to an empty chair, then later move a different person into that empty chair, and then move the first person again? That would be inefficient. So we ignore.
Thus answer.
Now I will produce code in C++.
Implementation steps in code:
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
int main() {
int n;
cin >> n;
vector<int> a(n);
vector<int> occ, empty;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] == 1) occ.push_back(i+1);
else empty.push_back(i+1);
}
int m = occ.size();
int p = empty.size();
if (m == 0) {
cout << 0 << endl;
return 0;
}
vector<ll> prev(p+1, 0);
for (int i = 1; i <= m; i++) {
vector<ll> cur(p+1, INF);
// cur[j] for j < i will be INF, we don't care
for (int j = i; j <= p; j++) {
ll cost = prev[j-1] + abs(occ[i-1] - empty[j-1]);
cur[j] = cost;
if (j > i) cur[j] = min(cur[j], cur[j-1]);
}
prev = move(cur);
}
cout << prev[p] << endl;
return 0;
}
Now check a random test: n=2, occ=[1], empty=[2] => dp: m=1, p=1: i=1, j=1: cost=0+|1-2|=1, answer=1. This makes sense: move from 1 to 2 takes 1 minute.
But wait: is n>=2, so fine.
Now consider n=2, occ=[2], empty=[1] => distance 1.
Now consider n=4, occ=[2,3] but m=2 > n/2? n/2=2, so m=2 allowed. empty=[1,4]. DP: occ sorted [2,3], empty [1,4]. i=1: j=1: cost=0+|2-1|=1 -> cur[1]=1; j=2: cost=0+|2-4|=2 -> cur[2]=2; min(2,1)=1; so prev=[INF,1,1]. i=2: j=2: cost=prev[1]+|3-4|=1+1=2; answer=2. That is sum 1+1? Actually matching 2->1 (1), 3->4 (1) total 2. Yes.
So all good.
Now check with n=5000 worst-case DP. 6.25e6 operations, each with simple arithmetic, fine.
Thus answer.
But I recall a known Codeforces problem: "Armchairs" (CF Round #???). Indeed I've seen this problem. The solution is exactly DP. Some people also used DP with n^2.
Now let's think about possible pitfalls: There is a nuance: The DP we used is standard for minimum cost matching between two sequences when we can skip elements in the larger one. It is correct.
Now we can finalize.
But is there any scenario where using the same empty chair as temporary for multiple persons could reduce total time? We argued that direct sum of distances is lower bound. However, consider a scenario with three occupied and three empty, but distances are such that moving a person to a far empty chair, then moving another into that person's original chair, etc., could result in total distance less than the sum of direct distances? For that to happen, the sum of distances for two persons via chain might be less than sum of direct distances due to triangle inequality being strict? But triangle inequality is |a-c| ≤ |a-b|+|b-c|. So sum of two direct distances from a to A and b to B might be larger than sum of distances if we swap? Actually the total distance of two moves: if we swap positions, we could move a to B and b to A. That's still direct. If we need to use an intermediate, it's at least as much. So no.
But consider a scenario where the empty chairs are not enough? Actually m = p? Then we must match one-to-one. So direct matching is the only way.
Thus answer.
Now think about the DP initial values: prev array size p+1, all 0. That's fine for i=0.
For cur, we need to set INF. We can set cur[0..i-1] = INF, but we only set from i to p. However, we haven't set cur[0..i-1] explicitly; they remain whatever default INF we gave to whole vector. That's fine.
Now just output.
Now final note: The DP uses long long, but answer fits in int. But we can use long long to be safe.
Thus final answer.
But I will double-check the DP logic with another example: occ=[1,100,101], empty=[2,3,102] (m=3, p=3). DP:
prev: [0,0,0,0]
i=1:
j=1: cost=0+|1-2|=1 -> cur[1]=1
j=2: cost=0+|1-3|=2 -> cur[2]=2 -> min with cur[1]=1 -> 1
j=3: cost=0+|1-102|=101 -> cur[3]=101 -> min with cur[2]=1 -> 1
So prev = [INF,1,1,1]
i=2:
j=2: cost=prev[1]+|100-3|=1+97=98 -> cur[2]=98
j=3: cost=prev[2]+|100-102|=1+2=3 -> cur[3]=3 -> min with cur[2]=98 => 3
So prev = [INF, INF,98,3]? Actually after i=2, cur = [INF, INF?, 98, 3] but we have cur[0] INF, cur[1] INF (since j from 2 to 3 only, we set cur[1] remains INF). So prev becomes [INF, INF, 98, 3].
i=3:
j=3: cost=prev[2]+|101-102|=98+1=99 -> cur[3]=99 -> answer = 99. But maybe there is better matching: 1->2 (1), 100->102 (2), 101->3? No 3 is taken? Actually we can match 1->2 (1), 100->102 (2), 101->?? empty left: 3? But 3 is empty but we haven't used it. That would be 1+2 + |101-3| = 1+2+98=101. Or match 1->3 (2), 100->2 (98), 101->102 (1) total=101. Or match 1->2 (1), 100->3 (97), 101->102 (1) total=99. That's 99. So DP gave 99. Good.
Now check if there is a better matching maybe 1->2 (1), 100->102 (2), 101->3? That's 1+2+98=101. So 99 is minimal.
Thus DP correct.
Now we can finalize.
I'll produce the final solution in C++. Also include necessary headers.
Time to produce final answer.
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n;
cin >> n;
vector<int> occupied, empty;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (x == 1)
occupied.push_back(i + 1); // 1‑based positions
else
empty.push_back(i + 1);
}
int m = occupied.size(); // number of people
int p = empty.size(); // number of empty chairs
// No one to move
if (m == 0) {
cout << 0 << '\n';
return 0;
}
// dp[j] = minimal cost after processing some prefix of occupied chairs
vector<ll> prev(p + 1, 0);
for (int i = 1; i <= m; ++i) {
vector<ll> cur(p + 1, INF);
// j must be at least i, otherwise we cannot match i people
for (int j = i; j <= p; ++j) {
ll direct = prev[j - 1] + abs(occupied[i - 1] - empty[j - 1]);
cur[j] = direct;
// option: skip the j‑th empty chair
if (j > i)
cur[j] = min(cur[j], cur[j - 1]);
}
prev = move(cur);
}
cout << prev[p] << '\n';
return 0;