[Programming thinking and practice of CSP-M1 A] cuckoo East adventure

Subject description:

There is a ring, connected end to end by the letters of the alphabet composition. A ring pointer initially pointing to a. Each time a grid rotated clockwise or counterclockwise. For example: a clockwise to b, counterclockwise to z. Now there is a character string, needs to find how many times can turn pointer point to a string of letters.

Input formats:

Enter only one line, it is a string.

Sample Input:

zeus

Output formats:

At least to the number of output revolutions.

Sample Output:

18

Ideas:

To make the minimum number of revolutions, i.e., every time when the revolution number of cells reach the next letter to be minimal. Therefore, to consider each rotation is clockwise or counterclockwise rotation can turn relatively small number of cells.
Set pointer is currently pointing to letters as before, to get to the next letter is next.
If the next lexicographically larger than before, when the grid of the number of revolutions clockwise next-before (here, a subtraction ASCII); if the number of cells is rotated counterclockwise 26-1 + before-next;
if lexicographically next smaller than before, If the clockwise rotation of the number of cells 26-1 + next-before; if the number of cells is rotated counterclockwise before-next;
by studying the above formula and the absolute value operation, a portion of the case can be combined.

Code:

#include <iostream>
#include <string>
#include<cmath>
using namespace std;

int main(int argc, char** argv) {
 string str;
 int temp=0,count=0,c[3];
 cin>>str;
 for(int i=0;i<str.size();i++)
 {
  int a=str[i]-'a';
  c[0]=abs(a-temp);
  c[1]=abs(26+a-temp);
  c[2]=abs(26-a+temp);
  int min=0;
  for(int i=1;i<3;i++)
   if(c[i]<c[min])
    min=i;
  count+=c[min];
  temp=a;
 }
 cout<<count<<endl;
 return 0;
}
Published 25 original articles · won praise 8 · views 539

Guess you like

Origin blog.csdn.net/weixin_44034698/article/details/104870656