题意是说给你一个串,然后任意删去一个位置的数字,然后求整个串相邻两个数的差的绝对值的最大值,最后问你这个最大值的期望值 * 串的长度 等于多少。
先观察,发现每个位置的值来源一定是剩余位置的最大值 和 当前位置前一个值和当前位置后一个值的差,这两个中大的那个,所以我先将所有两个数的差的绝对值求出来,排个序,然后去枚举每个位置,去排好序的序列中看,如果这个值因为当前值被删除所以不能用的话就找下一个,然后和新产生的差值进行比较,选最大的那个,加到最后答案里。
后来看了题解,其实只要预处理一下就行了,处理从头到每个位置的差值的最大值,和从尾部到每个位置的差值的最大值,然后再枚举每个位置,新产生的值和前两个比较,选最大的那个即可。这样子只要n的效率,排序需要nlogn,不过也能过。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n;
__int64 num[100005];
__int64 ans;
struct node
{
__int64 re;
int pos;
}rec[100005];
bool cmp(node a, node b)
{
return a.re > b.re;
}
int main(void)
{
int T;
scanf("%d", &T);
while (T--)
{
ans = 0;
scanf("%d", &n);
memset(rec, 0, sizeof rec);
for (int i = 0; i < n; i++)
scanf("%I64d", &num[i]);
for (int i = 1; i < n; i++)
{
rec[i].re = abs(num[i] - num[i - 1]);
rec[i].pos = i;
}
sort(rec + 1, rec + n, cmp);
if (rec[1].pos == 1)
ans += rec[2].re;
else
ans += rec[1].re;
if (rec[1].pos == n - 1)
ans += rec[2].re;
else
ans += rec[1].re;
for (int i = 1; i < n - 1; i++)
{
int j = 1;
for (; (rec[j].pos == i || rec[j].pos == i + 1) && j < n; j++);
ans += max(rec[j].re, abs(num[i + 1] - num[i - 1]));
}
printf("%I64d\n", ans);
}
return 0;
}