题意
定义一个序列的权值为相邻两项的差的绝对值,你可以翻转一次 \([l, r]\) 并使得权值最小。
\(n \le 3 \times 10 ^ 5\)。
Sol
显然考虑翻转一次 \([i, j]\) 的方案。
当前贡献便为:
\[|a_{i - 1} - a_{j}| + |a_{j + 1} - a_{i}| - |a_{i - 1} - a_{i}| - |a_{j + 1} - j| \]但是这样绝对值很多,很难处理。
考虑使用一个线段表示 \(a_{i - 1} \to a_i\)。
注意到两条线段有贡献,显然两条线段相交或包含,并且需要满足线段的方向相同。
直接把所有相邻的线段预处理出来,分成两组分别处理即可。
Code
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#include <vector>
#define ll long long
#define pii pair <int, int>
using namespace std;
#ifdef ONLINE_JUDGE
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<< 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;
#endif
int read() {
int p = 0, flg = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') flg = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
p = p * 10 + c - '0';
c = getchar();
}
return p * flg;
}
void write(ll x) {
if (x < 0) {
x = -x;
putchar('-');
}
if (x > 9) {
write(x / 10);
}
putchar(x % 10 + '0');
}
bool _stmer;
#define fi first
#define se second
const int N = 3e5 + 5;
ll solve(vector <pii> &isl) {
ll ans = 0; int lst = -1;
sort(isl.begin(), isl.end());
for (auto k : isl)
ans = max(ans, (ll)min(lst, k.se) - k.fi), lst = max(lst, k.se);
return 2ll * ans;
}
array <int, N> s;
bool _edmer;
int main() {
cerr << (&_stmer - &_edmer) / 1024.0 / 1024.0 << "MB\n";
vector <pii> isl;
int n = read();
ll res = 0;
for (int i = 1; i <= n; i++) s[i] = read();
for (int i = 2; i <= n; i++) res += abs(s[i] - s[i - 1]);
for (int i = 2; i <= n; i++)
if (s[i - 1] < s[i]) isl.push_back(make_pair(s[i - 1], s[i]));
ll ans = 0;
ans = max(solve(isl), ans), isl.clear();
for (int i = 2; i <= n; i++)
if (s[i - 1] > s[i]) isl.push_back(make_pair(s[i], s[i - 1]));
ans = max(solve(isl), ans);
for (int i = 1; i <= n - 1; i++)
ans = max(ans, (ll)abs(s[i] - s[i + 1]) - abs(s[1] - s[i + 1]));
for (int i = 2; i <= n; i++)
ans = max(ans, (ll)abs(s[i] - s[i - 1]) - abs(s[n] - s[i - 1]));
write(res - ans), puts("");
return 0;
}
标签:Pancakes,ll,ans,ARC119E,int,isl,include,define
From: https://www.cnblogs.com/cxqghzj/p/18459738