cf Educational Codeforces Round 127 (Rated for Div. 2) D题
You are given a sequence of nn integers a1,a2,…,ana1,a2,…,an. You are also given xx integers 1,2,…,x1,2,…,x.
You are asked to insert each of the extra integers into the sequence aa. Each integer can be inserted at the beginning of the sequence, at the end of the sequence, or between any elements of the sequence.
The score of the resulting sequence a′a′ is the sum of absolute differences of adjacent elements in it (∑i=1n+x−1|a′i−a′i+1|)(∑i=1n+x−1|ai′−ai+1′|).
What is the smallest possible score of the resulting sequence a′a′?
Input
The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of testcases.
The first line of each testcase contains two integers nn and xx (1≤n,x≤2⋅1051≤n,x≤2⋅105) — the length of the sequence and the number of extra integers.
The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤2⋅1051≤ai≤2⋅105).
The sum of nn over all testcases doesn't exceed 2⋅1052⋅105.
Output
For each testcase, print a single integer — the smallest sum of absolute differences of adjacent elements of the sequence after you insert the extra integers into it.
Example
input
Copy
4 1 5 10 3 8 7 2 10 10 2 6 1 5 7 3 3 9 10 10 1 4 10 1 3 1 2
output
Copy
9 15 31 13
Note
Here are the sequences with the smallest scores for the example. The underlined elements are the extra integers. Note that there exist other sequences with this smallest score.
- 1–,2–,3–,4–,5–,101_,2_,3_,4_,5_,10
- 7–,7,6–,4–,2,2–,1–,3–,5–,8–,107_,7,6_,4_,2,2_,1_,3_,5_,8_,10
- 6,1–,1,2–,5,7,3,3,9,10,10,16,1_,1,2_,5,7,3,3,9,10,10,1
- 1,3,1–,1,2,2–,3–,4–,5–,6–,7–,8–,9–,10–––1,3,1_,1,2,2_,3_,4_,5_,6_,7_,8_,9_,10_
思路:当遇到绝对值相减时,我们的第一反应就要是两值的大小关系,这两个数(或者是区间)是单调的,在两端中间的数可有可无,最后的值是最大值减最小值,能够区间的数做出快速处理。 这里对区间的要求是必须是单调的,可以单调增也可以单调减,可以不是严格的单调,但必须是单调!
对于区间的连续求绝对值之差,要我们往里面插数,因为是绝对值,所以最小值是0,不可能让数组的得分变得更小,所以我们产生尽可能多的0贡献,我们可以将 x 中符合数组中的最大最小值的数全部插入,只不过可能会分好多段插入,得看原数组的值了,让他们符合单调性一段一段插入,这样产生的分数还是原来数组产生的。现在去观察原数组,数组的最大值maxx可能在最右,最左,和中间;最小值minn也是可能在最左,最右,中间。我们只要分别考虑这6种情况计算即可,此时是去掉 x 中间的数的,因为它们能产生0贡献。我们以最大值举例。
结论:
1.原数组一定会产生贡献,我们可以在数组的最大与最小值之间插入值从minn到maxx区间的值,只要插入时是单调的插入即可,从而不会产生影响。
2.区间符合单调性只计算区间两端。
完整代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;
const int N=2e5+10;
int a[N];
void solve()
{
int n,x;
cin>>n>>x;
int maxx=0,minn=1e9;
for(int i=1;i<=n;i++)
{
cin>>a[i];
maxx=max(maxx,a[i]);
minn=min(minn,a[i]);
}
int sum=0;
for(int i=2;i<=n;i++)
{
sum+=abs(a[i]-a[i-1]);
}
if(minn>1) sum+=min(abs(a[1]-1),min(abs(a[n]-1),2*(minn-1)));
if(maxx<x) sum+=min(abs(a[1]-x),min(abs(a[n]-x),2*(x-maxx)));
cout<<sum<<endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}