// Author: Lukas Polacek
// Date: September 29th, 2010
// Algorithm: Try to use all gaps between non-'A' characters
// Complexity: O(N)

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <stack>
#include <cstdio>
using namespace std;

#define rep(i,a,b) for(__typeof(b) i=a; i<(b); ++i)

typedef pair<int, int> pii;
typedef vector<int> vi;
int main()
{
    int t; scanf("%d", &t);
    while (t--)
    {
        string s;
        cin >> s;

        int n = s.size(), work = 0;
        vi pos;
        rep(i,0,n)
        {
            work += min(s[i] - 'A', 'Z' - s[i] + 1);
            if (s[i] != 'A' || i == 0)
                pos.push_back(i);
        }

        int res = 1234567890;
        rep(i,0,pos.size())
        {
            int a = pos[i], b = n - pos[(i+1) % pos.size()];
            if (a > b) swap(a, b);
            res = min(res, 2 * a + b + work);
        }
        res = min(res, min(pos.back(), n - pos[0]) + work);

        printf("%d\n", res);
    }
}
