#include <bits/stdc++.h>   using namespace std;   int flow, n, m, S, T, tot, x, y;   int g[3000], dis[3000], pre[3000];   int Next[50000], adj[50000], f[50000], c[50000];   bool used[3000];   queue<int> q;   int ans = 0;   int calc[110][30];   string t, s;   void add(int x, int y, int flow, int cost) {     adj[tot] = y;     c[tot] = cost;     f[tot] = flow;     Next[tot] = g[x];     g[x] = tot++;     adj[tot] = x;     c[tot] = -cost;     f[tot] = 0;     Next[tot] = g[y];     g[y] = tot++;   }   bool spfa() {     for (int i = 1; i <= T; i++) dis[i] = 1 << 23;     dis[S] = 0;     memset(used, 0, sizeof(used));     while (!q.empty()) q.pop();     q.push(S);     used[S] = true;     int p;     while (!q.empty()) {       x = q.front();       used[x] = false;       p = g[x];       while (p != -1) {         y = adj[p];         if (f[p] && dis[x] + c[p] < dis[y]) {           dis[y] = dis[x] + c[p];           pre[y] = p;           if (!used[y]) {             used[y] = true;             q.push(y);           }         }         p = Next[p];       }       q.pop();     }     return dis[T] != 1 << 23;   }   int path() {     int del = 1 << 23;     int p = T;     while (p != S) {       if (f[pre[p]] < del) del = f[pre[p]];       p = adj[pre[p] ^ 1];     }     p = T;     while (p != S) {       f[pre[p]] -= del;       f[pre[p] ^ 1] += del;       p = adj[pre[p] ^ 1];     }     flow += del;     return del * dis[T];   }   void solve() {     memset(pre, 0, sizeof(pre));     while (spfa()) ans += path();     if (flow != t.size())       cout << -1 << endl;     else       cout << ans << endl;   }   int main() {     cin >> t;     cin >> n;     memset(g, -1, sizeof(g));     tot = 0;     S = 26 * (n + 1) + n + 1;     T = S + 1;     for (int i = 1; i <= n; i++) {       cin >> s >> x;       for (int j = 0; j < s.size(); j++) calc[i][s[j] -  a ]++;       add(S, 26 * (n + 1) + i, x, 0);     }     for (int i = 0; i < t.size(); i++) calc[n + 1][t[i] -  a ]++;     for (int i = 0; i < 26; i++) add(26 * n + i + 1, T, calc[n + 1][i], 0);     for (int i = 1; i <= n; i++)       for (int j = 0; j < 26; j++) {         add(26 * (n + 1) + i, (i - 1) * 26 + j + 1, 1 << 23, 0);         add((i - 1) * 26 + j + 1, 26 * n + j + 1, calc[i][j], i);       }     solve();     return 0;   }   