time limit per test
1 second
memory limit per test
256 megabytes
You are given an array of distinct integers x1,x2,…,xnx1,x2,…,xn and an integer ss.
Initially, you are at position pos=spos=s on the XX axis. In one step, you can perform exactly one of the following two actions:
- Move from position pospos to position pos+1pos+1.
- Move from position pospos to position pos−1pos−1.
A sequence of steps will be considered successful if, during the entire journey, you visit each position xixi on the XX axis at least once. Note that the initial position pos=spos=s is also considered visited.
Your task is to determine the minimum number of steps in any successful sequence of steps.
Input
Each test consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers nn and ss (1≤n≤101≤n≤10, 1≤s≤1001≤s≤100) — the number of positions to visit and the starting position.
The second line of each test case contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1001≤xi≤100). It is guaranteed that for all 1≤i<n1≤i<n, it holds that xi<xi+1xi<xi+1.
Output
For each test case, output the minimum number of steps in any successful sequence of steps.
Example
Input
Copy
12
1 1
1
1 2
1
1 1
2
2 1
2 3
2 2
1 3
2 3
1 2
3 1
1 2 3
3 2
1 3 4
3 3
1 2 3
4 3
1 2 3 10
5 5
1 2 3 6 7
6 6
1 2 3 9 10 11
Output
Copy
0 1 1 2 3 2 2 4 2 11 8 15
Note
In the first test case, no steps need to be taken, so the only visited position will be 11.
In the second test case, the following path can be taken: 2→12→1. The number of steps is 11.
In the third test case, the following path can be taken: 1→21→2. The number of steps is 11.
In the fifth test case, the following path can be taken: 2→1→2→32→1→2→3. The number of steps is 33.
解题说明:此题是一道数学题,为了保证所有点均到达,需要计算从起始点到两端的距离分别是多少,然后再比较即可。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n, s;
scanf("%d%d", &n, &s);
int x[101];
for (int i = 0; i < n; i++)
{
scanf("%d", &x[i]);
}
int steps = 0;
int min = x[0];
int max = x[n - 1];
int step1 = abs(s - min) + (max - min);
int step2 = abs(max - s) + (max - min);
steps = (step1 < step2) ? step1 : step2;
printf("%d\n", steps);
}
return 0;
}