#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define debug cout<<"debug"<<endl
mt19937 rd(time(0));
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> PII;
const double eps = 1e-8;
const double PI = 3.14159265358979323;
const int N = 110, M = 2*N, mod = 998244353;
const int INF = 0x3f3f3f3f;
struct Node{
ll a, b; int st = 0;
};
void solve()
{
int n; cin>>n;
ll l[2] = {INF, INF};
vector<Node> p(n);
for(int i = 0; i<n; i++) cin>>p[i].a;
ll sum = 0;
for(int i = 0; i<n; i++)
{
cin>>p[i].b;
sum += abs(p[i].a - p[i].b);
if(p[i].a == p[i].b) continue;
if(p[i].a>p[i].b) p[i].st = 1, swap(p[i].a, p[i].b);
}
// 将所有ai bi化为a<b的区间, 记录当前区间的状态, 若是a<b则是0正序状态, 否则为反序状态并更新为正序状态
sort(p.begin(), p.end(), [&](Node x, Node y)
{
if(x.b != y.b) return x.b<y.b;
return x.a<y.a;
});
ll mx = 0;
// 从最大的右端开始, 每次记录当前状态的最小左端, 如当前为 ai = 1, bi = 3 为ai<bi 可记录正序minl = ai = 1,
// 到下一个区间 为 (swap前)aj = 3 bj = 1, 为aj>bj 有反序的最小左端l = ai, 此时交换ai aj ,即为最大的减小区间差 然后记录当前状态的最小左端
// 贪心进行更新, 找到最大可更新区间
for(int i = n-1; i>=0; i--)
{
int f = p[i].st;
if(l[f^1]<p[i].b) mx = max(mx, p[i].b-max(l[f^1], p[i].a));
l[f] = min(l[f], p[i].a);
}
cout<<sum-mx*2<<endl;
}
int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int T;
T = 1;
// cin>>T;
while(T -- )
{
solve();
}
return 0;
}
2023牛客多校-H-Matches(贪心+思维)
最新推荐文章于 2024-07-04 16:16:29 发布