## B - 1D Keyboard Editorial by en_translator

For a character \(c\), let \(X_c\) be the coordinate of the key corresponding to the character \(c\).

Then, what we need to find is \(|X_A-X_B|+|X_B-X_C|+\ldots+|X_Y-X_Z|\).

If we can find \(S\) from \(X\), the sought value can be found using a `for`

statement.

In an ordinary programming language, an array is indexed by a non-negative integer, but not by a character.
For the implementation of this problem, one can correspond the integer \(0\) to `A`

, \(1\) to `B`

, \(\ldots\), and \(25\) to `Z`

, so that the aforementioned \(X\) can be managed as an array.
Alternatively, you may use an associative array with its key being a character type.

Sample code (C++):

```
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
vector<int> x(26);
for (int i = 0; i < 26; ++i)
x[s[i] - 'A'] = i;
int ans = 0;
for (int i = 0; i < 25; ++i)
ans += abs(x[i] - x[i + 1]);
cout << ans << endl;
}
```

Sample code (Python3):

```
s = input()
x = [0] * 26
for i in range(26):
x[ord(s[i]) - ord("A")] = i
ans = 0
for i in range(25):
ans += abs(x[i] - x[i + 1])
print(ans)
```

posted:

last update: