CF1513F Swapping Problem(模型转化)
题目描述
You are given 2 arrays and , both of size . You can swap two elements in 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 ( ).
The second line contains integers ( ).
The third line contains integers ( ).
输出格式
Output the minimum value of .
题意翻译
给定 和两个长度为 的数组 ,最多交换一次 中的两个位置的值(可以不交换)。
最小化 。
;。
输入输出样例
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 , so that it becomes .
Therefore, the minimum possible value of this sum would be .
In the second example, we can swap the first and second elements. So, our answer would be .
题解
可以很容易的计算出 \(ans = \sum_{i=1}^n |a_i-b_i|\) 的值,但是我们需要交换一对,使得 ans 尽量小
假设交换 \(i,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;
}

浙公网安备 33010602011771号