“范式杯”2023牛客暑期多校训练营1 H题解

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值