#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
long long n,m;
const long long Maxn=25;
long long a[Maxn],s[Maxn],p[Maxn];
inline long long read()
{
	long long s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
int main()
{
	m=n=read();
	p[0]=1ll;
	for(long long i=1;i<=19;++i)
	p[i]=p[i-1]*10ll;
	long long ans=0ll,tmp=0ll;
	for(long long i=3;i<=19;i+=3)
	{
		if(n>=p[i])ans+=(p[i]-p[i-3])*tmp;
		else
		{
			ans+=(n-p[i-3]+1ll)*tmp;
			break;
		}
		++tmp;
	}
	printf("%lld\n",ans);
	return 0;
}
#include<bits/stdc++.h>
#define pb emplace_back
#define AI(i) begin(i), end(i)
using namespace std;
using ll = long long;
#ifdef KEV
#define DE(args...) kout("[ " + string(#args) + " ] = ", args)
void kout() {cerr << endl;}
template<class T1, class ...T2>
void kout (T1 v, T2 ...e) { cerr << v << ' ', kout(e...); }
template<class T>
void debug(T L, T R) { while (L != R) cerr << *L << " \n"[next(L)==R], ++L; }
#else
#define DE(...) 0
#endif
const int MAX_N = 300010, inf = 1e9;
int solve() {
	string a = "atcoder", b;
	cin >> b;
	{
		string c = b;
		sort(AI(c), greater<>());
		DE(a, c);
		if (a >= c)
			return -1;
	}
	int res = inf, cur = 0;
	if (a < b) return 0;
	for (int i = 0;i < a.size();++i) {
		if (i == b.size()) break;
		if (a[i] < b[i]) {
			res = min(res, cur);
			break;
		}
		for (int j = i+1;j < b.size();++j) {
			if (a[i] < b[j]) {
				res = min(res, j-i + cur);
				DE(i, j-i+cur);
			}
		}
		int p = -1;
		for (int j = i;j < b.size();++j)
			if (b[j] == a[i]) {
				p = j;
				break;
			}
		if (p == -1) break;
		while (p > i)
			swap(b[p], b[p-1]), --p, ++cur;
	}
	assert(res < inf);
	return res;
}
signed main() {
	ios_base::sync_with_stdio(0), cin.tie(0);
	int T;
	cin >> T;
	while (T--)
		cout << solve() << endl;
}
