HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 ≤ fi ≤ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
The first line contains a positive integer n (1 ≤ n ≤ 2·105) — the number of fragments.
The second line contains n different integers fi (1 ≤ fi ≤ n) — the number of the fragment written in the i-th sector.
Print the only integer — the number of time units needed to read the file.
3
3 1 2
3
5
1 3 5 4 2
10
In the second example the head moves in the following way:
- 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
- 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
- 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
- 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
题意:有n个碎片,各自有各自的编号,散乱排布,从第编号为1的碎片开始,依次通过编号2,3,4,....,n的碎片为完成工作。问至少需要几步才能完成
比如样例中的1 3 5 4 2
1到2需要四步, 2到3需要3步,3到4需要2步,4到5只需一步。4+2+3+1 = 10
方法:建立结构体中包含编号和位置,给编号排序后相邻编号位置差的绝对值的和即为所求
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2 * 1e5 + 5;
struct node{
int loc;//位置
int id;//编号
};
long long ans;
int n;
node a[maxn];
bool cmp(node a, node b)
{
return a.id < b.id;
}
int main()
{
while(scanf("%d", &n) != EOF)
{
ans = 0;
for(int i = 1;i <= n;i++)
{
scanf("%d", &a[i].id);
a[i].loc = i;
}
sort(a+1, a+n+1, cmp);
for(int i = 2;i <= n;i++)
{
ans += (long long)fabs(a[i].loc - a[i-1].loc);
}
printf("%I64d\n", ans);
}
return 0;
}