Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
File size: 890 Bytes
d3f4f72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <algorithm>
#include <iostream>
using namespace std;

const int INF = 1e6;

string S;
int K;
int dist[26][26];

int solve() {
  for (int i = 0; i < 26; i++) {
    for (int j = 0; j < 26; j++) {
      dist[i][j] = (i == j) ? 0 : INF;
    }
  }
  cin >> S >> K;
  for (int i = 0; i < K; i++) {
    char a, b;
    cin >> a >> b;
    dist[a - 'A'][b - 'A'] = 1;
  }
  for (int k = 0; k < 26; k++) {
    for (int i = 0; i < 26; i++) {
      for (int j = 0; j < 26; j++) {
        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
      }
    }
  }
  int ans = INF;
  for (int i = 0; i < 26; i++) {
    int curr = 0;
    for (char c : S) {
      curr += dist[c - 'A'][i];
    }
    ans = min(ans, curr);
  }
  return ans == INF ? -1 : ans;
}

int main() {
  int T;
  cin >> T;
  for (int t = 1; t <= T; t++) {
    cout << "Case #" << t << ": " << solve() << endl;
  }
  return 0;
}