def cost(x, y):
dif = abs(x - y)
return min(dif, 26 - dif)
def solve():
import sys
data = sys.stdin.read().split()
if not data:
return
t = int(data[0])
index = 1
output_lines = []
for _ in range(t):
s = data[index]
index += 1
# Assert the size is within the expected range.
assert 9 <= len(s) <= 200000
target = "EIJOORSSU"
# Create vector aa with indices 1..9 corresponding to the target letters.
aa = [0] * 10
for i in range(1, 10):
aa[i] = ord(target[i-1]) - ord('A')
# Build a new string p by taking up to 9 occurrences of each letter (A-Z)
freq = [0] * 26
for ch in s:
freq[ord(ch) - ord('A')] += 1
p_chars = []
for ch in range(ord('A'), ord('Z') + 1):
mx = 9
while mx > 0 and freq[ch - ord('A')] > 0:
freq[ch - ord('A')] -= 1
mx -= 1
p_chars.append(chr(ch))
s = "".join(p_chars)
# Create a 1-indexed list bb representing the numeric value of each character in s.
n = len(s)
bb = [0] * (n + 1)
for i in range(1, n + 1):
bb[i] = ord(s[i-1]) - ord('A')
ans = float('inf')
# Try all shifts from 0 to 13 inclusive.
for cnt in range(14):
# Copy arrays a and b from aa and bb.
a = aa[:] # a[1..9] will be modified.
b = bb[:] # b[1..n] will be modified.
# Adjust a[1..9]
for i in range(1, len(target) + 1):
a[i] = (aa[i] - cnt + 26) % 26
# Adjust b[1..n]
for i in range(1, n + 1):
b[i] = (bb[i] - cnt + 26) % 26
# Sort the lists from index 1 onward (keeping 1-indexing)
a[1:] = sorted(a[1:])
b[1:] = sorted(b[1:])
# Initialize dp table with dimensions (n+1) x (len(target)+1) = (n+1) x 10.
M_val = int(5e5)
dp = [[M_val] * (len(target) + 1) for _ in range(n + 1)]
dp[0][0] = 0
# Fill dp table.
for i in range(1, n + 1):
dp[i][0] = 0
max_j = min(i, len(target))
for j in range(1, max_j + 1):
dp[i][j] = min(dp[i][j], dp[i-1][j])
dp[i][j] = min(dp[i][j], dp[i-1][j-1] + cost(b[i], a[j]))
ans = min(ans, dp[n][len(target)])
output_lines.append(str(ans))
sys.stdout.write("\n".join(output_lines))
if __name__ == '__main__':
solve()