Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
Input
The first line contains one number n (2 ≤ n ≤ 50).
The second line contains 2·n integer numbers w1, w2, ..., w2n, where wi is weight of person i (1 ≤ wi ≤ 1000).
Output
Print minimum possible total instability.
Examples
Input
2
1 2 3 4
Output
1
Input
4
1 3 4 6 3 4 100 200
Output
5
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 solve: There are 2n people, we have n-1 tandem kayaks (2-seater) and 2 single kayaks. So total kayaks: (n-1) + 2 = n+1, but wait that sums to n-1 tandem + 2 single = n+1 kayaks, and we have 2n people. Since tandem kayak carries 2, single carries 1, total capacity: 2*(n-1) + 2 = 2n-2+2 = 2n, correct.
We need to assign people to these kayaks to minimize total instability (sum over tandem kayaks of absolute weight differences; singles contribute 0). We can choose which people go to singles, and which to tandem pairs.
Goal: minimize sum of absolute differences of the chosen pairs.
We have 2n people, we need to select 2 people to be singles? Actually singles: there are 2 single kayaks, so exactly 2 people will be alone (each in a single kayak). The remaining 2n-2 = 2(n-1) people will be paired into n-1 tandem kayaks.
Thus we need to pick two individuals to be singles, and pair up the rest into n-1 disjoint pairs to minimize sum of absolute differences of each pair.
This is a combinatorial optimization problem: we have weights w_i. We can think of sorting the weights, because pairing sorted order often yields optimal for minimizing sum of absolute differences when all must be paired (i.e., pairing adjacent in sorted order). However, we have the option to leave two people out (singles). That could allow us to skip some large gaps that would otherwise contribute to instability.
We need to find the best subset of 2 persons to be singles, and then pair the rest optimally. Since n <= 50, 2n <= 100, we could consider brute force: iterate over all pairs (i,j) to be singles, then pair the remaining sorted list optimally. However, there are C(2n,2) ~ up to 4950 possible pairs; then for each we need to compute optimal pairing of remaining 2n-2 numbers. For each set, optimal pairing to minimize sum of absolute differences (when all must be paired) is indeed pairing adjacent in sorted order after sorting the set. This is a known result: For an even number of numbers, the minimum sum of absolute differences when partitioning into pairs (each number used exactly once) is achieved by sorting and pairing adjacent numbers (like matching problem). It can be proved by exchange argument: any crossing pairs can be swapped to reduce or not increase sum. So yes.
Thus, for a given set of 2n-2 numbers (sorted), the minimal sum = sum_{k=1}^{(2n-2)/2} (a_{2k} - a_{2k-1}) if we pair a1 with a2, a3 with a4, etc. Actually we have to decide which pairing. The known optimal is to pair the numbers in sorted order sequentially: (1st,2nd), (3rd,4th), ... . This yields minimal total absolute difference. This is because for sorted numbers, the min sum of absolute differences in a perfect matching is achieved by pairing adjacent sorted elements. This is essentially a classic DP problem (matching on line) but with all numbers, the greedy works? Let's double-check. Consider numbers sorted: x1 ≤ x2 ≤ x3 ≤ x4. Options: pair (x1,x2)+(x3,x4) sum = (x2-x1)+(x4-x3). Alternative (x1,x3)+(x2,x4) sum = (x3-x1)+(x4-x2). Compare: (x2-x1)+(x4-x3) vs (x3-x1)+(x4-x2) = (x3-x2)+(x2-x1)+(x4-x2) = (x2-x1)+(x4-x2)+(x3-x2) = (x2-x1)+(x4-x3)+( (x3-x2)+(x2-x3? Wait need to compute properly: Actually (x3-x1)+(x4-x2) = (x3-x2 + x2-x1) + (x4-x3 + x3-x2) = (x2-x1)+(x4-x3)+2(x3-x2). So it's larger by 2(x3-x2) if x3 > x2. So indeed adjacent pairing is better. More generally, by a swapping argument: For any optimal matching that is not adjacent, we can adjust to reduce sum. So yes.
Thus, given a sorted list of even size, min sum = sum_{i} (a_{2i} - a_{2i-1}) for i from 1 to m where m = (2n-2)/2 = n-1.
Now, we need to choose two indices to remove from the original sorted list (2n numbers) to minimize this sum. Let the sorted weights be w[1..2n] (1-indexed sorted ascending). After removing two people at positions p and q (p<q) in this sorted order, we have 2n-2 numbers. But the sorted order of the remaining is just the original sorted list with two gaps. Then we pair adjacent in that reduced list: i.e., we consider the reduced sorted array of length 2n-2, and then pair (1st with 2nd), (3rd with 4th), ... etc. That yields sum of differences of consecutive pairs after removal.
But careful: after removal, the adjacency pairing might cross the gap? Actually, we have a new sorted list; we then take pairs as (new[1], new[2]), (new[3], new[4]), ... . This is equivalent to pairing the original sorted indices with some skipping.
Thus the problem reduces to: Given sorted array a[1..2n], choose two indices to remove (distinct) to minimize sum_{i=1}^{n-1} (b_{2i} - b_{2i-1}), where b is the sorted list after removal.
We can compute this efficiently. Since n <= 50, 2n <= 100, we could just brute-force over all pairs of indices to remove (i,j) with i<j, and then compute the resulting sum directly by constructing the reduced list (or computing sum using indices). O((2n)^2 * (2n)) naive O(n^3) ~ 100^3=1e6 (maybe 1e6). Actually (2n choose 2) ~ 4950, and for each we need to compute sum over n-1 pairs. Building the reduced list is O(2n) per pair, total about 4950*100 = 495k, trivial. So we can just brute force.
But maybe there is more elegant solution, but brute is fine.
Edge Cases: Note that singles have instability 0, but we must have exactly two singles; we cannot have more singles or fewer. So we must remove exactly two.
Check examples:
Example1: n=2, 2n=4, weights 1 2 3 4. Sorted: 1,2,3,4. Need to choose two singles, remaining two will form one tandem. The instability is |difference| of the pair. We can choose singles as any two; the tandem will be the other two. So we can minimize by picking singles such that the remaining pair has minimal difference. The answer: min over pairs? Options: singles: {1,2} -> tandem {3,4} diff=1; {1,3} -> {2,4} diff=2; {1,4} -> {2,3} diff=1; {2,3} -> {1,4} diff=3; {2,4} -> {1,3} diff=2; {3,4} -> {1,2} diff=1. Minimum 1. Output 1 matches.
Example2: n=4, 2n=8, weights: 1 3 4 6 3 4 100 200. Sorted: let's sort: 1,3,3,4,4,6,100,200. Choose 2 singles, remaining 6 people -> 3 tandem pairs. Compute min. Brute force: We'll test later.
Given constraints, brute works.
But we must be careful: Could there be a scenario where pairing the remaining not strictly adjacent in the original sorted order is optimal? But we argued for a given set, pairing adjacent in that set is optimal. So our approach yields the optimal total instability.
Thus algorithm:
Read n, read list w (size 2n).
Sort w.
Initialize ans = large number.
For i from 0 to 2n-1:
for j from i+1 to 2n-1:
// remove indices i and j (0-indexed)
Create a new list b = w without these two indices.
// b size = 2n-2
total = 0
for k from 0 to (2n-2)/2 - 1: // iterate over pairs
total += b[2k+1] - b[2k] // because sorted
ans = min(ans, total)
Print ans.
Complexity O((2n)^3) but with simple constant: actually constructing b each time is O(2n). Could avoid copying by computing sum using indices directly: We have sorted a. After removing positions i and j, the pairing of the reduced list can be computed by considering that the pairing will group consecutive elements in the reduced list. So we can compute sum directly by iterating through the original indices, skipping i and j, and grouping the remaining into pairs as we go. But not necessary.
Given n=50, 2n=100, (10099/2)=4950 loops, each summing over up to 49 pairs, so operations ~ 495049 ~ 242k, trivial.
Thus answer.
But before finalizing, confirm that pairing after removal is indeed the optimal for that set. Yes.
Potential nuance: Could there be scenario where we want to assign the singles such that the remaining set is not optimally paired as adjacent? But we already proved that for any given set, the minimal sum is achieved by pairing sorted adjacent. So we are correct.
Therefore, solution straightforward.
Double-check with example2: Let's compute manually maybe using code mental.
We'll test all pairs? Let's find optimum known answer 5. So our method should produce 5.
Sorted a = [1,3,3,4,4,6,100,200]. 2n=8, need remove 2, pair remaining 6. We can brute think: For each removal, compute sum of differences of three pairs (adjacent in reduced list). Let's compute.
We'll list all removal pairs (i<j indices 0..7). But many. We'll try to find min.
Observation: large numbers 100 and 200 are far; we likely want to remove them as singles because if they are paired, difference 100 large. So possible removal includes both 100 and 200. Also maybe one of them with something else? But if we remove both large ones, remaining: [1,3,3,4,4,6]. Sorted: [1,3,3,4,4,6]. Pair adjacent: (1,3)=2, (3,4)=1, (4,6)=2 => total = 5. That's exactly answer 5. So removing 100 and 200 yields 5. Could there be better? Try remove 100 and 6? remaining: [1,3,3,4,4,200]. Pairs: (1,3)=2, (3,4)=1, (4,200)=196 => total 199 >5. Remove 200 and 6: similar. Remove both large ones is best. Remove 1 and 200? remaining: [3,3,4,4,6,100] => pairs: (3,3)=0, (4,4)=0, (6,100)=94 => total 94. Remove 1 and 100? [3,3,4,4,6,200] => (3,3)=0, (4,4)=0, (6,200)=194 =>194. Remove 1 and 3? many combos but likely >=5. So answer 5.
Thus works.
Edge Cases: n=2 gave correct.
Now n can be 2 to 50, but note for n=2 we have 2n=4, removal of 2 leaves 2, pairing exactly one pair. Our algorithm works.
Time to implement.
Implementation details:
Read integer n.
Read list w of size 2*n.
Sort w.
Initialize ans as something large (like INF = 10**9).
For i in range(2n):
for j in range(i+1, 2n):
b = []
for k in range(2n):
if k != i and k != j:
b.append(w[k])
# b length = 2n-2
total = 0
for t in range(0, len(b), 2):
total += b[t+1] - b[t]
ans = min(ans, total)
print ans.
Alternatively, we can compute total directly without constructing b: using a pointer and skipping i,j. But easier to construct.
Memory: fine.
But note: In Python, constructing b each time by iterating over all 2n might be okay for 4950*100 = 495k appends.
Alternatively, we can compute as:
total=0
p = 0
while p < len(b):
total += b[p+1]-b[p]
p+=2
Works.
Thus code.
Now, let's consider if there is any possibility that pairing the remaining by not simply taking consecutive pairs after sorting could be better? But that's the proven optimum for that set. So fine.
One nuance: The problem says "instability of a single kayak is always 0". So singles don't contribute. So we are correct.
Thus solution is simple.
But wait: Could there be a scenario where pairing the remaining with other than adjacent in sorted order gives a lower sum? For a set of numbers, the minimum weight perfect matching on a line (where edge weights are absolute differences) is indeed achieved by matching adjacent numbers. This is a known result: The minimum cost matching for points on a line is to pair them in order. It can be solved by DP, but the greedy works because the graph is a line and we want a perfect matching. Actually, consider four numbers: 1, 2, 3, 100. Adjacent pairing: (1,2)=1, (3,100)=97 total=98. Alternate pairing: (1,3)=2, (2,100)=98 total=100. So adjacent better. Another: 1, 4, 5, 6. Adjacent: (1,4)=3, (5,6)=1 total=4. Alternate: (1,5)=4, (4,6)=2 total=6. So adjacent better. So yes.
But is it always? Proof: For sorted a1 ≤ a2 ≤ ... ≤ a_{2m}. Suppose we have a matching that is not the adjacent one. Then there exists a smallest index i such that a_i is matched with some a_j, j>i+1, and a_{i+1} is matched with some a_k, k>i+1. Then consider swapping: match a_i with a_{i+1} and a_j with a_k. Show that new sum ≤ old sum. Because difference after swapping: (a_{i+1}-a_i) + (max(a_j,a_k)-min(a_j,a_k)) ≤ (a_j - a_i) + (a_k - a_{i+1})? Actually need to compare: old: (a_j - a_i) + (a_k - a_{i+1}) (assuming j<k). new: (a_{i+1}-a_i) + (a_k - a_j). Compare: old - new = (a_j - a_i) + (a_k - a_{i+1}) - (a_{i+1} - a_i) - (a_k - a_j) = a_j - a_i + a_k - a_{i+1} - a_{i+1} + a_i - a_k + a_j = 2a_j - 2a_{i+1} = 2(a_j - a_{i+1}). Since j > i+1, a_j ≥ a_{i+1}, so old - new ≥ 0 => old >= new. So swapping does not increase total. So by repeated swaps we can transform any matching to the adjacent pairing without increasing cost. So adjacent pairing is optimal.
Thus correct.
Thus code is straightforward.
But wait: Could we also consider the possibility that the two singles are not distinct? No, they are distinct persons. So remove two distinct indices.
Implementation in Python:
def solve():
import sys
data = sys.stdin.read().split()
if not data: return
n = int(data[0])
w = list(map(int, data[1:]))
w.sort()
m = 2*n
INF = 10**9
ans = INF
for i in range(m):
for j in range(i+1, m):
b = []
for k in range(m):
if k != i and k != j:
b.append(w[k])
total = 0
for t in range(0, len(b), 2):
total += b[t+1] - b[t]
ans = min(ans, total)
print(ans)
But careful: In example n=2, len(b) = 2, t from 0 to 0 step 2, total += b[1]-b[0]. Works.
Complexity fine.
However, we can also do dynamic programming? Not needed.
But is there any twist? The problem statement says "There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks." So n could be 2? Then we have n-1 = 1 tandem kayak, and 2 singles -> total 2n=4 people, capacity: 1*2 + 2 = 4, okay. For n=1? But constraint says n ≥ 2, so fine.
Thus done.
But wait: Could there be scenario where we want to assign the singles to be those that are not the two we removed from sorted list? Actually, after sorting, we consider removal of indices in sorted order; but the actual people are distinct. The sorted list gives a specific order. Removing indices from sorted list corresponds to selecting those individuals as singles. Since we consider all pairs (i,j) across the sorted list, we are exploring all combinations of two people as singles. So that's correct.
Thus answer.
But is it possible that the optimal assignment does not pair the remaining exactly as adjacent in the sorted order after removal? We've proven that for any set, the minimal pairing sum is achieved by adjacent pairs in sorted order. So no issue.
Thus final answer.
But wait: I realize there is a nuance: After removing two indices, the sorted order of the remaining is fixed. But is it always optimal to pair them as (1st,2nd), (3rd,4th), ...? Since we are taking the sorted list, indeed that's the optimal pairing for that set. So yes.
Therefore, solution is correct.
Now, test with some random small cases to verify with brute force of all possible assignments (which is huge but for small n we can manually test) but we trust.
But let's also check scenario: Suppose we have weights [1,2,100,101]. n=2 (since 2n=4). If we remove {1,2} singles, tandem diff = |101-100|=1 -> total=1. If we remove {100,101} singles, tandem diff = |2-1|=1 -> total=1. If remove {1,100} singles, tandem diff = |101-2|=99 -> 99. So min 1. Our algorithm sorted = [1,2,100,101]. Remove indices (0,1) -> b=[100,101] -> diff=1; (0,2) -> b=[2,101] -> diff=99; (0,3) -> b=[2,100] -> diff=98; (1,2) -> b=[1,101] -> diff=100; (1,3) -> b=[1,100] -> diff=99; (2,3) -> b=[1,2] -> diff=1; min=1. correct.
Now, larger test: n=3 (2n=6). We have 2 singles, 2 tandem kayaks? Actually n-1=2 tandem, plus 2 singles => total capacity 2*2+2=6. So we need to remove 2 singles, pair 4 into 2 tandems. For sorted a[1..6], after removing two indices i<j, we need to pair remaining 4 numbers optimally. That's sum of two differences: (b2-b1)+(b4-b3) where b sorted after removal.
Our brute works.
But maybe there is a more efficient way: Since n ≤ 50, O(n^3) fine.
One more nuance: Are we allowed to choose which kayak is tandem or single? Yes. So our selection is valid.
Now, let's consider if there is any reason to consider that the two singles could be in the same tandem? No, singles are in separate kayaks, so they are not paired.
Thus solution done.
But wait: Could the arrangement of tandem kayaks have any effect? For example, if we have two tandem kayaks, the pairing is just pairing of the people. The order of kayaks does not matter. So it's just a partition into pairs.
All good.
Now, we should also think about whether the optimal solution could involve not pairing the remaining as adjacent because maybe some pairs crossing would yield smaller sum due to the singles being removed? But we already proved that for a given set, the minimal sum of absolute differences for perfect matching is achieved by pairing adjacent sorted numbers. So no.
Hence, implement.
But maybe we can do a DP approach that might be more efficient, but not needed.
Thus final answer.
But I recall a Codeforces problem: "Kayaking" maybe? It might be from CF 263A? Actually there is a problem named "Kayaking" on CF? I'm not sure. But the typical solution is O(n^2) or O(n^3) with n up to 50.
Wait, I recall a Codeforces problem "Kayaking" where n is up to 50 and they need to compute minimal instability. The solution often is: sort the weights, then for each possible pair of singles (i,j) you compute the sum of adjacent differences of the remaining. That is exactly our approach.
So answer.
Now, write the final code.
But we might improve by precomputing differences? Not needed.
Second sample: n=4, w sorted as earlier; we computed answer 5. So should print 5.
Now, one more test: Suppose n=3, weights: 1 1 100 100 200 200. Sorted: 1,1,100,100,200,200. We need to remove two singles, then pair four. Likely remove the two 200? Then remaining: 1,1,100,100 -> pairs: (1,1)=0, (100,100)=0 total 0. That's min? Maybe remove one 200 and one 100? Let's see. If remove 200 and 200 -> total 0. If remove 200 and 100? remaining: 1,1,100,200 -> pairs: (1,1)=0, (200-100)=100 -> total 100. So min 0. Our algorithm: Remove indices (4,5) (if zero-indexed, positions of 200s) yields b sorted [1,1,100,100] total 0. So answer 0.
Thus correct.
Edge: All weights equal: w_i = constant. Then any pairing yields 0. So answer 0.
Ok.
Now, we may also consider the scenario where there are many duplicate weights.
Implementation: Since we read w, and 2n numbers, we need to ensure we read exactly 2n numbers. We'll just read all.
Now, finalize solution.
But is there any tricky part about "minimum possible total instability"? Might there be a case where we want to assign more than two singles? No, we have exactly two single kayaks. So it's fixed.
Thus final answer.
One more thought: The problem might be solved by sorting and then DP that selects singles and pairs? But brute is simpler.
Now, double-check constraints: n up to 50, so 2n up to 100. Our O((2n)^3) is okay.
But we should check that Python can handle 4950 iterations each with inner loop 100 for building b and maybe 50 for summing. That's about 500k operations, fine.
Now, let's produce final code with function solve().
But wait: There's a potential catch: The number of kayaks: n-1 tandem + 2 singles = n+1 kayaks. The problem statement says "exactly n - 1 tandem kayaks and 2 single kayaks." So indeed the only constraint is that exactly two people go alone. Good.
Thus answer.
Now, ensure we handle input correctly.
We can also simplify: Instead of building b list, we can directly compute the sum by scanning the sorted list and maintaining a list of indices we keep, but building b is easier.
But building b each time is O(2n) and we need to allocate a new list; but it's fine.
However, in Python, to reduce overhead, we could pre-sort, and then for each i<j, compute total by iterating through the indices and pairing as we go, but that might be more code. Simplicity is okay.
Now, just produce the final solution.
But let's think about alternative approach: Because we always pair adjacent after removal, we can think of removing two elements from the sorted array, and then the total sum becomes sum_{k=1}^{n-1} (a_{p_{2k}} - a_{p_{2k-1}}) where p are the indices of kept elements in order. Could we compute efficiently by DP? Not needed.
Now, final answer.
We'll write code.
Test manually with some random to be safe: For n=2, sorted w [10,20,30,40], min? Remove (10,20) -> pair (30,40) diff=10; remove (30,40) -> diff=10; others worse. So answer 10. Our algorithm: remove (0,1) -> b[30,40] diff=10; (0,2) -> b[20,40] diff=20; (0,3) -> b[20,30] diff=10; (1,2) -> b[10,40] diff=30; (1,3) -> b[10,30] diff=20; (2,3) -> b[10,20] diff=10; min=10. Good.
Now for n=3: w = [1, 50, 51, 100, 101, 150]. Sorted: 1,50,51,100,101,150. We need to remove two singles, pair four. Likely best: remove 1 and 150? Then remaining 50,51,100,101 -> pairs (50,51)=1, (100,101)=1 total=2. Remove 1 and 100? remaining 50,51,101,150 -> (50,51)=1, (150-101)=49 total=50. Remove 1 and 101: (50,51)=1, (150-100)=50 total=51. Remove 50 and 150: (1,51)=50, (100,101)=1 total=51. Remove 51 and 150: (1,50)=49, (100,101)=1 total=50. Remove 100 and 101: (1,50)=49, (51,150)=99 total=148. So min 2. Our algorithm should find 2.
Now, test code by mental: For i=0 (1), j=5 (150): b = [50,51,100,101] -> total = (51-50)+(101-100)=1+1=2. Good.
Thus works.
Ok.
Now, final answer: Provide code.
But wait: In some languages, we need to handle input reading properly. In Python, reading from stdin is fine.
We can also speed up: Not needed.
One more nuance: The problem might be from Codeforces, where multiple test cases? No, only one case. So read once.
Thus produce final.
Now, can we reduce to O(n^2)? Possibly: For each possible removal pair, compute sum of differences quickly using prefix sums? But not needed.
We'll provide the O(n^3) solution.
Now, I'll produce final response. ```python
import sys
def solve() -> None:
data = sys.stdin.read().split()
if not data:
return
n = int(data[0])
weights = list(map(int, data[1:]))
weights.sort()
m = 2 * n
INF = 10 ** 9
ans = INF
code
# try every pair of indices to become the two singles
for i in range(m):
for j in range(i + 1, m):
# build the sorted list of the remaining 2n-2 persons
b = []
for k in range(m):
if k != i and k != j:
b.append(weights[k])
# compute total instability: sum of differences of consecutive pairs
total = 0
for t in range(0, len(b), 2):
total += b[t + 1] - b[t]
if total < ans:
ans = total
print(ans)