#include<bits/stdc++.h>
using namespace std;
#define MAXN 100005
#define lowbit(x) (x&-x)
#define reg register
#define mkpr make_pair
#define fir first
#define sec second
typedef long long LL;
typedef unsigned long long uLL;
const int INF=0x3f3f3f3f;
const int mo=998244353;
const LL jzm=2333;
const int iv2=499122177;
const double Pi=acos(-1.0);
typedef pair<int,int> pii;
const double PI=acos(-1.0);
template<typename _T>
_T Fabs(_T x){return x<0?-x:x;}
template<typename _T>
void read(_T &x){
	_T f=1;x=0;char s=getchar();
	while(s>'9'||s<'0'){if(s=='-')f=-1;s=getchar();}
	while('0'<=s&&s<='9'){x=(x<<3)+(x<<1)+(s^48);s=getchar();}
	x*=f;
}
template<typename _T>
void print(_T x){if(x<0){x=(~x)+1;putchar('-');}if(x>9)print(x/10);putchar(x%10+'0');}
int k,cnt1[15],cnt2[15],pow10[10]={1,10,100,1000,10000,100000};
char str1[15],str2[15];LL sum1,sum2;
void sakura(LL num){
	int tmp1=0,tmp2=0;
	for(int i=1;i<=9;i++)tmp1+=i*pow10[cnt1[i]],tmp2+=i*pow10[cnt2[i]];
	sum1+=num;if(tmp1>tmp2)sum2+=num;return ;
}
signed main(){
	read(k);scanf("\n%s\n%s",str1+1,str2+1);
	if(k==1){puts("0");return 0;}
	for(int i=1;i<5;i++)cnt1[str1[i]-'0']++,cnt2[str2[i]-'0']++;
	for(int i=1;i<10;i++)
		for(int j=1;j<10;j++){
			LL tmp=k-cnt1[i]-cnt2[i];cnt1[i]++;
			tmp*=1ll*(k-cnt1[j]-cnt2[j]);cnt2[j]++;
			//printf("%d %d:%d\n",i,j,tmp);
			if(cnt1[i]<=k&&cnt2[j]<=k)sakura(tmp);
			cnt1[i]--;cnt2[j]--;
		}
	printf("%.5f\n",1.0*sum2/sum1);
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define FORR2(x,y,arr) for(auto& [x,y]:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------

int T,N;
string S,A="atcoder";

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	A+='a'-1;
	
	cin>>T;
	while(T--) {
		cin>>S;
		int ret=1010101;
		FOR(i,8) {
			string T=S;
			int sum=0;
			x=0;
			for(j=0;j<T.size();j++) {
				if(x<i) {
					if(T[j]==A[x]) {
						sum+=j-x;
						rotate(T.begin()+x,T.begin()+j,T.begin()+j+1);
						x++;
					}
				}
				else if(i==x) {
					if(T[j]>A[x]) {
						sum+=j-x;
						rotate(T.begin()+x,T.begin()+j,T.begin()+j+1);
						x=100;
						break;
					}
				}
			}
			if(x==100) ret=min(ret,sum);
		}
		
		if(ret==1010101) ret=-1;
		cout<<ret<<endl;
		
		
	}
}


int main(int argc,char** argv){
	string s;int i;
	if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
	FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
	cout.tie(0); solve(); return 0;
}
