--- /dev/null
+#include <stdio.h>
+#include <stdbool.h>
+#include <limits.h>
+#include <string.h>
+
+#define lookup(i, x1, x2) (i)[((x1)-'A')+((x2)-'A')*26]
+
+int main()
+{
+ char *buf = NULL;
+ size_t len;
+ char template[26*26] = {0};
+ unsigned long input1[26*26] = {0};
+ unsigned long input2[26*26] = {0};
+ unsigned long *input = input1;
+ unsigned long *newinput = input2;
+
+ int first = getchar();
+ int c, oldc = first;
+ unsigned long freq[26] = {0};
+ while ( (c = getchar()) != '\n') {
+ lookup(input, oldc, c) = 1;
+ oldc = c;
+ }
+
+ while (getline(&buf, &len, stdin) != -1) {
+ if (buf[0] == '\n')
+ continue;
+ lookup(template, buf[0], buf[1]) = buf[6];
+ }
+
+ for (int step = 0; step < 40; step++) {
+ for (char x = 'A'; x<='Z'; x++) {
+ for (char y = 'A'; y<='Z'; y++) {
+ char ins = lookup(template, x, y);
+ if (ins != '\0') {
+ unsigned long freq = lookup(input, x, y);
+ lookup(newinput, x, ins) += freq;
+ lookup(newinput, ins, y) += freq;
+ }
+ }
+ }
+ unsigned long *t = newinput;
+ newinput = input;
+ input = t;
+ memset(&newinput[0], 0, sizeof(input1));
+ }
+
+ for (char x = 'A'; x<='Z'; x++) {
+ for (char y = 'A'; y<='Z'; y++) {
+ freq[x-'A'] += lookup(input, x, y);
+ freq[y-'A'] += lookup(input, x, y);
+ }
+ }
+ freq[first-'A']++;
+ freq[oldc-'A']++;
+
+ unsigned long min = ULONG_MAX, max = 0;
+ for (int i = 0; i<26; i++) {
+ max = freq[i] > max ? freq[i] : max;
+ min = freq[i] > 1 && freq[i] < min ? freq[i] : min;
+ }
+
+ printf("%lu\n", max/2-min/2);
+}