Problem Description
Besides on the traditional classes,Baby Volcano also needs to learn how to take the express mails.
Usually express mails are stored in cabinets. In Baby Volcano's school,there are n cabinets in a row,numbered by 1 to n. The distance between two adjacent cabinets is 1, and the entrance is at the cabinet 1. Among all n cabinets,the one numbered k is special and it is used to enter the code and open the cabinet door.
Baby Volcano has m express mails to take,the i-th is in the cabinet ai.
Two express mails will not be stored in the same cabinet. Also there is no express mail in the cabinet k.
To prevent expresses from being stolen, Baby Volcano have to take these express mails one by one, starting at the entrance. Generally, if he wants to take the express mail i, he have to walk to cabinet k first to enter the code, and then walks to cabinet ai. After taking the last one,he walks to the entrance.
There are so many express mails to take, so Baby Volcano wants to find a taking order which minimize the distance he walks.Input
The first line contains one integer T(1≤T≤100),the number of testcases.
For each test cases,the first line contains three integer n,m,k(1≤k≤n≤109,1≤m<min(n,106))
The next line contains m integer,the i-th stand for ai(1≤ai≤n,ai≠k).
The input guarantees that ∑m≤2×106
**Note:Because of the large input,it is prefered to use scanf instead of cin.**Output
For each test case,Output a single line contains one integer,representing for the minimal walking distance.
Sample Input
2 10 2 5 6 7 10 2 5 3 4
Sample Output
14 10
题意:有一排快递柜编号为1到n,一共有m个快递,还有一个密码柜位于k,每次取快递都必须先到密码柜输入密码才能取到快递,相邻两个柜子之间的距离为1,问取走所有快递需要移动的最短距离是多少;
思路:1、先读入所有快递的位置然后对其从小到大排序,每次取快递都必须在对应快递柜和k之间往返一次,即答案加上2*abs(a[i]-k);
· 2 、 对于第一个快递需要特判,如果位于k的左边那么可以不用再特意取件,直接在往返起点的路程中即可取到;如果位于右边那么需要按照第一步的思路加上距离;
3、最后加上起点到k往返的距离即可
AC代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define ll long long
const int N=1000010;
int a[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<m;i++)
scanf("%d",&a[i]);
sort(a,a+m);
ll res=0;
for(int i=1;i<m;i++)
res+=2*abs(a[i]-k);
if(k<a[0])
{
res+=2*abs(a[0]-k);
res+=2*(k-1);
}
else
res+=2*(k-1);
printf("%lld\n",res);
}
}