Codeforces Round #376 (Div. 2) A. Night at the Museum —— 循环轴
题目链接: http://codeforces.com/contest/731/problem/A
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
The only line of input contains the name of some exhibit — the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Print one integer — the minimum number of rotations of the wheel, required to print the name given in the input.
zeus
18
map
35
ares
34
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
- from 'a' to 'z' (1 rotation counterclockwise),
- from 'z' to 'e' (5 clockwise rotations),
- from 'e' to 'u' (10 rotations counterclockwise),
- from 'u' to 's' (2 counterclockwise rotations).
题解:
很基础的一道题, 但是值得积累。
对于一条循环的数轴,就以0~9的数轴为例(9跟在0的后面,构成循环), 求now到next的最短距离:
情况1:不需要从尾越过头, 或者从头越过尾, dis = abs(next - now)。
情况2:需要从尾越过头, dis = (len-now) + next 。 第一部分为从now到尾的距离, 第二部分为从头到next的距离。
情况3:需要从头越到尾, dis = now + (len-next)。 第一部分为从now到头的距离, 第二部分为从尾到next的距离。
综上, 所以:最短距离 = min( abs(next-now), min( (len-now)+next, now+(len-next) ) )
代码如下:
#include <bits/stdc++.h> using namespace std; int main() { char s[1000]; cin>>s; int ans = 0, now = 0; for(int i = 0; i<strlen(s); i++) { int next = s[i] - 'a'; ans += min( abs(now-next), min( now+26-next, 26-now+next ) ); now = next; } cout<<ans<<endl; }