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_
思路:
1,左右之间插入两数之间的数,那么任意插,但不影响差值和
2,所以只需要考虑1和x,看原序列与1和x的关系
代码:
#include<bits/stdc++.h>
using namespace std;
#define rep(i,m,n) for(int i=m;i<=n;++i)
#define int long long
const int maxj=2e5+100;
// template<class t>void read(t &res){
// char c;t flag=1;
// while((c=getchar())>'9'||c<'0')if(c=='-')flag=-1;res=c-'0';
// while((c=getchar()<='9')&&c>='0')res=res*10+c-'0';res*=flag;
// }
int a[maxj];
vector<int>b;
void solve(){
int n,x;
cin>>n>>x;
int ans=0;
int mx=-1,mn=1e9,pos1=0,pos2=0;
rep(i,1,n){
cin>>a[i];
if(a[i]>mx)mx=a[i],pos1=i;
if(a[i]<mn)mn=a[i],pos2=i;
if(i>1)ans+=abs(a[i]-a[i-1]);
}
if(a[pos1]<x){//最大
if(pos1==1||pos1==n){
ans+=x-a[pos1];//边上加最值差
}else{
int add=(x-a[pos1])*2;
add=min(add,x-a[1]);
add=min(add,x-a[n]);
ans+=add;
}
}
if(a[pos2]>1){//最小
if(pos2==1||pos2==n){
ans+=a[pos2]-1;
}else{
int add=(a[pos2]-1)*2;
add=min(add,a[1]-1);//边界
add=min(add,a[n]-1);
ans+=add;
}
}
cout<<ans<<'\n';
}
int32_t main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t;
cin>>t;
while(t--)solve();
return 0;
}