#include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)

using namespace std;
struct Node{
    vector<int> next;
    int value;
    Node() : next(0xff, -1), value(-1) {}
};
vector<Node> nodes;
void insert(string s, int v){
    int p = 0;
    for(char c : s){
        if(nodes[p].next[c] == -1){
            nodes.push_back(Node());
            nodes[p].next[c] = nodes.size() - 1;
        }
        p = nodes[p].next[c];
    }
    nodes[p].value = v;
}
int main(){
    int n;
    int CASENUM = 1;
    while(cin >> n && n){
        nodes.clear();
        nodes.push_back(Node());
        vector<string> str(n);
        vector<int> vals(n);
        REP(i, n){
            cin >> str[i] >> vals[i];
            insert(str[i], vals[i]);
        }
        string s;
        cin >> s;

        vector<int> cur( nodes.size(), -1 );
        cur[0] = 0;
        for(char c : s){
            vector<int> next( nodes.size(), -1);
            for(int i = 0; i < nodes.size(); i++){
                if(cur[i] < 0) continue;
                int k = nodes[i].next[c];
                if(k == -1) continue;
                next[k] = max(next[k], cur[i]);
                if(nodes[k].value >= 0){
                    next[0] = max(next[0], cur[i] + nodes[k].value);
                }
            }
            cur.swap(next);
        }

        int m = cur[0];
        vector<int> dp(m + 1, INT_MAX);
        dp[0] = 0;
        for(int i = 0; i < m; i++){
            if(dp[i] == INT_MAX) continue;
            for(int j = 0; j < n; j++){
                int ni = i + vals[j];
                if(ni <= m) dp[ni] = min<int>(dp[ni], dp[i] + str[j].size());
            }
        }

        int answer = dp[m];

        assert(answer < INT_MAX);
        cout << "Case " << CASENUM++ << ": ";
        cout << answer << endl;
    }
    return 0;
}