Codeforces Round #376 (Div. 2) A. Night at the Museum

http://codeforces.com/problemset/problem/731/A

题意:
实现,z-a-b-c-d…….x-y-z-a这样的一个环形。
从a出发,给一个字符串,问,最短的移动距离是多少。
(26个字母的环形锁,给你密码问最走转几步)

PS:
输入:zeus
from ‘a’ to ‘z’ (1步),
from ‘z’ to ‘e’ (5步),
from ‘e’ to ‘u’ (10步),
from ‘u’ to ‘s’ (2步).
1 + 5 + 10 + 2 = 18.

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
using namespace std;

int main() {
string s;
cin >> s;
int res = 0, pos = 'a', dis;
for (char c : s) {
dis = abs(c - pos);
// 有个细节就是,如果b到a,b-a会是-1,所以要取绝对值。
res += min(dis, 26 - dis);
// 要么逆时针走要么顺时针走,取最小值即可
pos = c;
}
printf("%d\n", res);
return 0;
};