題目描述
You are given 2 arrays a a a and b b b , both of size n n n . You can swap two elements in b b b at most once (or leave it as it is), and you are required to minimize the value $$\sum_{i}|a_{i}-b_{i}|. $$
Find the minimum possible value of this sum.
輸入格式
The first line contains a single integer n n n ( 1≤n≤2⋅105 1 \le n \le 2 \cdot 10^5 1≤n≤2⋅105 ).
The second line contains n n n integers a1,a2,…,an a_1, a_2, \ldots, a_n a1,a2,…,an ( 1≤ai≤109 1 \le a_i \le {10^9} 1≤ai≤109 ).
The third line contains n n n integers b1,b2,…,bn b_1, b_2, \ldots, b_n b1,b2,…,bn ( 1≤bi≤109 1 \le b_i \le {10^9} 1≤bi≤109 ).
輸出格式
Output the minimum value of ∑i∣ai−bi∣ \sum_{i}|a_{i}-b_{i}| ∑i∣ai−bi∣ .
題意翻譯
給定 nnn 和兩個長度為 nnn 的陣列 a,ba,ba,b,最多交換一次 bbb 中的兩個位置的值(可以不交換)。
最小化 ∑i=1n∣ai−bi∣\sum_{i=1}^{n}|a_i-b_i|∑i=1n∣ai−bi∣。
n≤2×105n \le 2\times10^5n≤2×105;ai,bi≤109a_i,b_i\le 10^9ai,bi≤109。
輸入輸出樣例
- 5
- 5 4 3 2 1
- 1 2 3 4 5
- 4
- 2
- 1 3
- 4 2
- 2
說明/提示
In the first example, we can swap the first and fifth element in array b b b , so that it becomes [5,2,3,4,1] [ 5, 2, 3, 4, 1 ] [5,2,3,4,1] .
Therefore, the minimum possible value of this sum would be ∣5−5∣+∣4−2∣+∣3−3∣+∣2−4∣+∣1−1∣=4 |5-5| + |4-2| + |3-3| + |2-4| + |1-1| = 4 ∣5−5∣+∣4−2∣+∣3−3∣+∣2−4∣+∣1−1∣=4 .
In the second example, we can swap the first and second elements. So, our answer would be 2 2 2 .
題解
可以很容易的計算出 \(ans = \sum_{i=1}^n |a_i-b_i|\) 的值,但是我們需要交換一對,使得 ans 儘量小
假設交換 \(i,j\) 這兩對,那麼此時的答案應該為
\]
要找的這兩對應該滿足
\]
而且前者越大越好,後者越小越好,題目就像是一道二維偏序一樣,解決的思路就是先確定一維
看著這滿屏的絕對值,自然而然地想到了距離,不妨自己畫一下發現,當
b_j<a_i<a_j<b_i \\
a_i<b_j<a_j<b_i \\
b_j<a_i<b_i<a_j
\]
上述情況滿足時上面的不等式才會成立(當然以上只有 \(a_i<b_i\) 的情況,還有四種情況,請讀者自己思考)
這樣就擁有了降維的理由,我們可以按照 \(b\) 排序,這樣固定了右端點,根據上述推斷可以造成貢獻的有
\]
為了滿足區間的要求,需要進一步轉化為右端點\(\geq\)左端點
而根據貪心,固定右端點應該按照 \(b\) 升序排列,這樣可以滿足
\]
所以要計算的 \(|b_j-a_i|\) 由於 \(b_j\) 的確定,只要保留之前 \(a_i\) 的最小值就可以了
總體演算法複雜度 \(O(NlogN)\) 為排序的時間
const int N=3e5+5;
int n, m, _;
int i, j, k;
ll a[N];
ll b[N];
struct Node
{
ll x, y;
bool operator<(Node o){
return x<o.x;
}
int tag;
Node(ll x = 0, ll y = 0, int tag = 0) : x(x), y(y), tag(tag){}
}p[N];
signed main()
{
//IOS;
while(~sd(n)){
ll ans = 0;
rep(i, 1, n) sll(a[i]);
rep(i, 1, n) sll(b[i]), ans += abs(a[i] - b[i]);
rep(i, 1, n){
if(a[i] <= b[i]) p[i] = Node(a[i], b[i], 0);
else p[i] = Node(b[i], a[i], 1);
}
sort(p + 1, p + 1 + n);
ll maxx = 0;
ll ed[2] = {0, 0};
rep(i, 1, n){
ed[p[i].tag] = max(ed[p[i].tag], p[i].y);
if(!ed[p[i].tag ^ 1]) continue;
if(p[i].x <= ed[p[i].tag ^ 1]){
if(p[i].y <= ed[p[i].tag ^ 1]){
maxx = max(maxx, p[i].y - p[i].x);
continue;
}
maxx = max(maxx, ed[p[i].tag ^ 1] - p[i].x);
}
}
pll(ans - maxx * 2);
}
//PAUSE;
return 0;
}