1651C.md (2774B)
1 Source: https://codeforces.com/problemset/problem/1651/C 2 3 C. Fault-tolerant Network 4 5 time limit per test 6 7 2 seconds 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 There is a classroom with two rows of computers. There are $n$ computers in each row and each computer has its own grade. Computers in the first row have grades $a_1, a_2, \dots, a_n$ and in the second row — $b_1, b_2, \dots, b_n$. 22 23 Initially, all pairs of neighboring computers in each row are connected by wire (pairs $(i, i + 1)$ for all $1 \le i \lt n$), so two rows form two independent computer networks. 24 25 Your task is to combine them into one common network by connecting one or more pairs of computers from different rows. Connecting the $i$-th computer from the first row and the $j$-th computer from the second row costs $|a_i - b_j|$. 26 27 You can connect one computer to several other computers, but you need to provide at least a basic fault tolerance: you need to connect computers in such a way that the network stays connected, despite one of its computers failing. In other words, if one computer is broken (no matter which one), the network won't split into two or more parts. 28 29 What is the minimum total cost to make a fault-tolerant network? 30 31 Input 32 33 The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Next, $t$ cases follow. 34 35 The first line of each test case contains the single integer $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of computers in each row. 36 37 The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the grades of computers in the first row. 38 39 The third line contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$) — the grades of computers in the second row. 40 41 It's guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$. 42 43 Output 44 45 For each test case, print a single integer — the minimum total cost to make a fault-tolerant network. 46 47 Example 48 49 Input 50 51 ``` 52 2 53 54 3 55 56 1 10 1 57 58 20 4 25 59 60 4 61 62 1 1 1 1 63 64 1000000000 1000000000 1000000000 1000000000 65 ``` 66 67 Output 68 69 ``` 70 31 71 1999999998 72 ``` 73 74 Note 75 76 In the first test case, it's optimal to connect four pairs of computers: 77 78 1. computer $1$ from the first row with computer $2$ from the second row: cost $|1 - 4| = 3$; 79 2. computer $3$ from the first row with computer $2$ from the second row: cost $|1 - 4| = 3$; 80 3. computer $2$ from the first row with computer $1$ from the second row: cost $|10 - 20| = 10$; 81 4. computer $2$ from the first row with computer $3$ from the second row: cost $|10 - 25| = 15$; 82 83 In total, $3 + 3 + 10 + 15 = 31$. 84 85 In the second test case, it's optimal to connect $1$ from the first row with $1$ from the second row, and $4$ from the first row with $4$ from the second row.