[ARC119E] Pancakes题解

· · 题解

被反转的区间中,只有两端真正被影响了,其余的贡献不变。

因此,此题本质是说给若干二元组,可选择两个二元组,交换其中一个的第一项和另一个的第二项,最小化每个二元组元素差之和。

考虑二元组元素差的几何意义,即数轴上的线段长度。我们发现两个二元组表示的线段如果方向一致且相交,那么交换之后相当于去掉了相交部分。那么此题就变成了求线段最大相交。针对两个方向的线段,我们计算两次即可。

#include <bits/stdc++.h>
#define lowbit(x) (x & (-x))
#define max(a, b) ((a > b) ? a : b)
#define min(a, b) ((a < b) ? a : b)
using namespace std;
const int N = 300010;
long long n, a[N], org, ans, cnt, minn = 2e9, maxn = -2e9;
struct node
{
    long long st, en;
    bool operator < (const node &w) const {return st < w.st;}
}b[N];
inline void work()
{
    b[cnt + 1].st = b[cnt + 1].en = 0;
    sort(b + 1, b + cnt + 1);
    long long bj = -1, num = 0;
    for(int i = 1; i <= cnt; ++i)
    {
        num = max(num, min(bj, b[i].en) - b[i].st);
        bj = max(bj, b[i].en);
    }
    ans = min(ans, org - num * 2);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; ++i) cin >> a[i], minn = min(minn, a[i]), maxn = max(maxn, a[i]);
    for(int i = 1; i < n; ++i) org += abs(a[i + 1] - a[i]);
    ans = org;
    for(int i = 1; i < n; ++i) ans = min(ans, org - abs(a[i] - a[i + 1]) + abs(a[1] - a[i + 1]));
    for(int i = n; i > 1; --i) ans = min(ans, org - abs(a[i] - a[i - 1]) + abs(a[n] - a[i - 1]));
    cnt = 0;
    for(int i = 1; i < n; ++i) if(a[i] <= a[i + 1]) b[++cnt].st = a[i], b[cnt].en = a[i + 1];
    work();
    cnt = 0;
    for(int i = n; i > 1; --i) if(a[i] <= a[i - 1]) b[++cnt].st = a[i], b[cnt].en = a[i - 1];
    work();
    cout << ans << endl;
    return 0;
}