#include<bits/stdc++.h> usingnamespace std; using ll = longlong; using PII = pair<int, int>;
constint maxn = 1e3 + 5; unordered_map< string, int > dict; char g[maxn][maxn]; int n, m;
// 辅助 check 函数,校验候选词 boolcheck( string s, ll &ans ) { s += '#'; string cur = "";
for( char c : s ) { if( c != '#' ) { cur += c; continue; }
if( !cur.empty( ) ) { auto it = dict.find( cur ); if( it == dict.end( ) ) return0; ans += it->second; } cur = ""; } return1; }
voidsolve( ) { dict.clear( ); cin >> n >> m; for( int i = 1; i <= n; ++ i ) { for( int j = 1; j <= n; ++ j ) { cin >> g[i][j]; } }
for( int i = 1; i <= m; ++ i ) { string s; int score; cin >> s >> score; dict[s] += score; }
ll ans = 0; bool ok = 1;
// 扫描每一行 for( int i = 1; i <= n; ++ i ) { string word = ""; for( int j = 1; j <= n; ++ j ) word += g[i][j]; if( check( word, ans ) ) continue; ok = 0; break; }
if( ok == 0 ) { cout << "-1" << '\n'; return ; }
// 扫描每一列 for( int j = 1; j <= n; ++ j ) { string word = ""; for( int i = 1; i <= n; ++ i ) word += g[i][j]; if( check( word, ans ) ) continue; ok = 0; break; }