H,matchs
题意:n对ai,bi。d为n对ai-bi的绝对值相加,交换两个ai使得,d最小.n为1e6,ai,bi绝对值不大于1e9。
思路:
设一对数ai,bi.ai<bi为正序,ai>bi为逆序,易知要交换的两个ai,一定为一个正序和一个逆序的,而交换后产生的差值是交集的两倍。
做法为记录每对的正序逆序属性,然后若为逆序则交换ai,bi,按ai排序后,分别记录正序逆序的bi的值,因为是按照ai排序,所以一定满足交集左端点就是当前的ai值,交集右端点是当前的bi值(被包含情况),记录的最大bi值(相交情况)中较小的一个,o(n)更新即可,时间复杂度o(nlogn)
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll a[1005000];
ll b[1005000];
ll mx[2];//记录分别对正序,逆序而言的最右侧,
struct op {
ll a, b,pos;
};
vector<op> s;
bool cmp (op l,op r){
return l.a<r.a;
}
ll n;
int main() {
cin >> n;
ll ans=0;
mx[0]=-1145141919;
mx[1]=-1145141919;
for (ll x = 1; x <= n; x++) {
cin >> a[x];
}
for (ll x = 1; x <= n; x++) {
cin >> b[x];
op temp;
temp.a = a[x];
temp.b = b[x];
temp.pos=0;
ans+=max(a[x]-b[x],b[x]-a[x]);
if (a[x] <= b[x]) {
s.push_back(temp);
} else {
ll ui=temp.a;
temp.a=temp.b;
temp.b=ui;
temp.pos=1;
s.push_back(temp);
}
}
ll len=s.size();
sort(s.begin(),s.end(),cmp);
ll temp=0;
//cout<<ans<<endl;
for(ll x=0;x<len;x++){
op ui=s[x];
temp=max(temp,min(mx[!ui.pos],ui.b)-ui.a);
mx[ui.pos]=max(mx[ui.pos],ui.b);
}
cout<<ans-2*temp;
return 0;
}