圆环字符
一个圆环由字母表组成首尾相接的环,环上有一个指针,最初指向字母a,每次可以顺时针或者逆时针旋转一格。比如a逆时针旋转到z,顺时针旋转到b。现在给定一个字符串,求最少需要转多少次。
输入一行,是一个字符串;输出最少要转的次数。
sample input:
zeus
sample output:
18
数据范围:
数据点1-2 字符串长度小于等于10
数据点3-5 字符串长度小于等于100
数据点6-10 字符串长度小于等于10000
思路:
- 由于要输出转的次数,每转一次就是一个字母之间的距离,所以可以用两个字母之间的asc码的差值来表示从一个字母转到另一个字母需要经过的距离
- 一个字母到另一个字母有两种可能,要么逆时针转过去,要么顺时针转过去,那么最短的距离就是两个方式中较小的那个
- 由于距离都是正的,所以需要取绝对值。在代码中我写了一个转化绝对值的函数。当然,由于将asc转换成了整数进行计算,所以也可以用abs函数来做。
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int jue(int a)
{
if(a<0) return -a;
else if(a==0) return a;
else return a;
}
char str[10011];
int main()
{
cin>>str;
int length=strlen(str);
int sum=0;
int num=0;
for(int i=0;i<length;i++)
{
int temp=0;
temp=str[i]-'a';
sum+=min(jue(temp-num),26-jue(temp-num));
num=temp;
}
cout<<sum<<endl;
return 0;
}