#include<bits/stdc++.h>
using namespace std;
int main(){
	int t;
	scanf("%d",&t);
	string T="atcoder";
	while(t--){
		string S;
		cin>>S;
		int now=0,ans=1e9;
		bool op=S.size()>T.size();
		for(int i=0;i<S.size()&&i<T.size();++i){
			if(S[i]<=T[i]){
				bool ok=0;
				for(int j=i;j<S.size();++j){
					if(S[j]>T[i]){
						ans=min(ans,now+j-i);
					}
				}
				if(S[i]<T[i])
				for(int j=i;j<S.size();++j){
					if(S[j]>T[i])ans=min(ans,now+j-i);
					else if(S[j]==T[i]){
						ok=1;
						for(int k=j;k>i;--k)
							swap(S[k],S[k-1]);
						now+=j-i;
						break;
					}
				}
//				cerr<<"FK: "<<now<<" "<<ans<<endl;
				if(S[i]<T[i]&&!ok){now=1e9;break;}
			}
			else if(S[i]>T[i]){
				op=1;
				ans=min(ans,now);
				break;
			}
		}
		if(!op)now=1e9;
		if(min(ans,now)>1e8)puts("-1");
		else printf("%d\n",min(ans,now));
	}
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
string s,AT="atcoder";
int T;
void solve(){
	int ans=1e9,cur=0;
	for(int i=0;i<7;i++){
		int minpos=s.size(),minnp=s.size();
		for(int j=i;j<(int)s.size();j++){
			if(AT[i]<s[j]&&minpos==(int)s.size())minpos=j;
			if(AT[i]==s[j]&&minnp==(int)s.size())minnp=j;
		}
		if(minpos<s.size())ans=min(ans,cur+minpos-i);
		if(minnp<s.size()){
			cur+=minnp-i;
			for(int j=minnp;j>i;j--)s[j]=s[j-1];
		}else cur=1e9;
	}
	if((int)s.size()>7)ans=min(ans,cur);
	if(ans==1e9)puts("-1");
	else cout<<ans<<"\n";
}
int main(){
	cin>>T;
	while(T--){
		cin>>s;
		if(AT<s){
			puts("0");
			continue;
		}
		solve();
	}
}