#include using namespace std; /////////////////////////////////////////// const int INF = 100000000; using ll = long long int; using vi = vector; #define pb push_back #define all(x) (x).begin(),(x).end() #define rep(i,N) for(int i=0;ibool chmax(T &former, const T &b) { if (formerbool chmin(T &former, const T &b) { if (b> graph; using ue = unweighted_edge; int main(){ ll n,m; // int box[100000]; cin>>n; string ss; map s; vector k,k2; graph G(10000); int l=0; rep(i,n){ cin>>ss; k.push_back(ss); rep(j,ss.size()){ s.insert(make_pair(ss[j],l)); l++; } } rep(i,k.size()){ rep(j,k[i].size()-1){ ue e(k[i][j+1]); G[s[k[i][j]]].push_back(e); } } cin>>m; rep(i,m){ cin>>ss; k2.pb(ss); rep(j,ss.size()-1){ if(G[s[ss[j]]].size()==0){ ue e(ss[j+1]); G[s[ss[j]]].push_back(e); } } } bool feag=false; rep(i,k.size()){ if(find(all(k2),k[i])!=k2.end()){ feag = true; } } if(feag){ if(k2.size()==1){ cout< l) { break; } if (G[now].size() == 0)break; ans += G[now][0].to; //cout << ans << endl; now = s[G[now][0].to]; num++; } if (num == l) { flag = true; break; } else { num = 0; ans.clear(); } } if (flag == true) { cout << ans << endl; } else { cout << -1 << endl; } } return 0; }