#include <bits/stdc++.h>
using namespace std;
int n,k;
string niz[100];
string tren;
bool naso = 0;
int minlen = 1e9;
string koji;
int subst(string a, string b){
    int m = a.length();
    int m2 = b.length();
    if(m2 > m)return 0;
    int tr = 0;
    int res = 0;
    for(int i=0; i<m; i++){
        tr = 0;
        for(int j=i; j<m; j++){
            if(a[j] == b[tr])tr++;
            else
                break;
            if(tr == m2){
                res++;
                break;
            }
        }
    }
    return res;
}
bool provera(string x){
    for(int i=0; i<n; i++){
        if(subst(x,niz[i]) != 1)return 0;
    }
    return 1;
}
void radi(int ind){
    if(provera(tren)){
        naso = 1;
        if(tren.length() < minlen){
            koji = tren;
            minlen = tren.length();
        }
        return;
    }
    if(ind == 19)return;
    string pom = tren;
    tren += 'a';
    radi(ind+1);
    tren = pom;
    tren += 'b';
    radi(ind+1);
    tren = pom;

}
int Resi(int N, int K, int* L, char** A, char* S) {
    n = N;
    k = K;
    for(int i=1; i<=n; i++){
        string pom = "";
        for(int j=1; j<=L[i]; j++){
            pom += A[i][j];
        }
        niz[i - 1] = pom;
    }
    if(n == 2){
        ///a na b
        string a = niz[0];
        string b = niz[1];
        if(provera(a)){
            for(int i=0; i<a.length(); i++)S[i+1] = a[i];
            return a.length();
        }
        string pom = "";
        string tmp = a;
        reverse(b.begin(), b.end());
        for(int i=0; i<b.length(); i++){
            pom += b[i];
            a = tmp;
            a += pom;
            if(provera(a)){
                for(int i=0; i<a.length(); i++)S[i+1] = a[i];
                return a.length();
            }
        }
        reverse(b.begin(), b.end());
        swap(a,b);
        if(provera(a)){
            for(int i=0; i<a.length(); i++)S[i+1] = a[i];
            return a.length();
        }
         pom = "";
         tmp = a;
         reverse(b.begin(), b.end());
        for(int i=0; i<b.length(); i++){
            pom += b[i];
            a = tmp;
            a += pom;
            if(provera(a)){
                for(int i=0; i<a.length(); i++)S[i+1] = a[i];
                return a.length();
            }
        }
        return -1;
    }
    if(k == 2){
        for(int i=0; i<n; i++){
            for(int j=0; j<niz[i].length(); j++){
                if(niz[i][j] != 'a' && niz[i][j] != 'b')return -1;
            }
        }
        //cout << subst("aaaababa" , "abab") << endl;
        radi(0);
        if(naso){
            tren = koji;
            for(int i=0; i<tren.size(); i++){
                S[i+1] = tren[i];
            }
            return tren.size();
        }
        else
            return -1;
    }
}