/*
	[NWERC'10] HIGHSCORE
	by: Jan Kuipers
*/

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main () {

	int runs;
	cin >> runs;

	while (runs--) {

		string s;
		cin >> s;
		int N=s.size();
		
		int change = 0;
		for (int i=0; i<N; i++)
			change += min((26+s[i]-'A')%26, (26+'A'-s[i])%26);

		int res = N;

		for (int times=0; times<2; times++) {
			
			for (int i=0; i<N; i++) {
				int j=i+1;
				while (j!=i && s[j]=='A') j=(j+1)%N;
				res = min(res, i + (N+i-j)%N);
			}

			reverse(s.begin()+1,s.end());
		}

		cout << res + change << endl;
	}
	
	return 0;
}
