/* Problem URL: https://codeforces.com/problemset/problem/237/E */ #include using namespace std; #define V vector #define rmin(a, b) a = min(a, b) #define rmax(a, b) a = max(a, b) #define rep(i, lim) for (size_t i = 0; i < (lim); i++) #define nrep(i, s, lim) for (size_t i = s; i < (lim); i++) #define repv(i, v) for (auto &i : (v)) #define fillv(v) for (auto &itr_ : (v)) { cin >> itr_; } #define sortv(v) sort(v.begin(), v.end()) #define all(v) (v).begin(), (v).end() using vi = vector; using vvi = vector; using vvvi = vector; using vvvvi = vector; using ll = long long; using vl = vector; using vvl = vector; using vvvl = vector; using vvvvl = vector; template auto operator<<(ostream &os, const vector &vec)->ostream& { os << vec[0]; for (size_t i = 1; i < vec.size(); i++) { os << ' ' << vec[i]; } os << '\n'; return os; } template auto operator>>(istream &is, vector &vec)->istream& { for (auto &i : vec) { is >> i; } return is; } template auto operator<<(ostream &os, const vector> &vec)->ostream& { for (auto &i : vec) { os << i[0]; for (size_t j = 1; j < i.size(); j++) { os << ' ' << i[j]; } os << '\n'; } return os; } template auto operator>>(istream &is, vector> &vec)->istream& { for (auto &i : vec) { for (auto &j : i) { is >> j; } } return is; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string a; cin >> a; vi acount(26, 0); int tmp = 0; repv(i, a) { if (acount[i - 'a'] == 0) { tmp++; } acount[i - 'a']++; } int n; cin >> n; size_t size = n + 2 + tmp; vector> graph(size); vector> cost(size, vector(size, 0)); vector> capacity(size, vector(size, 0)); auto addedge = [&](int u, int v, int c, int p){ graph[u].push_back(v); graph[v].push_back(u); cost[u][v] = c; cost[v][u] = -c; capacity[u][v] = p; }; vi act(26, -1); int v = 1; rep(i, 26) { if (acount[i] > 0) { act[i] = v; addedge(v, size - 1, 0, acount[i]); v++; } } int start = v; for (size_t i = 1; i <= n; i++) { string b; int lol; cin >> b >> lol; vi bcount(26, 0); repv(j, b) { bcount[j - 'a']++; } rep(j, 26) { if (bcount[j] > 0 && acount[j] > 0) { addedge(v, act[j], i, bcount[j]); } } addedge(0, v, 0, lol); v++; } int inf = INT32_MAX >> 1; vector p(size, inf); vector d(size, -1); int s = 0; int t = size - 1; auto bfs = [&](){ d[s] = 0; vector inq(size, false); queue q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for (auto v : graph[u]) { if (capacity[u][v] > 0 && d[v] > d[u] + cost[u][v]) { d[v] = d[u] + cost[u][v]; p[v] = u; if (!inq[v]) { inq[v] = true; q.push(v); } } } } return d[t] != inf; }; vector vis(n * 2 + 2, false); int flow = 0; int c = 0; while (flow < a.size()) { fill(d.begin(), d.end(), inf); fill(p.begin(), p.end(), -1); if (!bfs()) { break; } int f = inf; int cur = t; while (cur != s) { f = min(f, capacity[p[cur]][cur]); cur = p[cur]; } flow += f; c += f * d[t]; cur = t; while (cur != s) { capacity[p[cur]][cur] -= f; capacity[cur][p[cur]] += f; cur = p[cur]; } } if (flow < a.size()) { cout << "-1\n"; return 0; } cout << c << '\n'; }