#include <limits.h>
#include <string.h>
+struct template { char x1; char x2; char ins; };
+
#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 ntemplate = 0;
+ struct template template[100];
+ unsigned long input1[26*26] = {0}, input2[26*26] = {0};
+ unsigned long *input = input1, *newinput = input2;
int first = getchar();
- int c, oldc = first;
+ int c, last = first;
unsigned long freq[26] = {0};
while ( (c = getchar()) != '\n') {
- lookup(input, oldc, c) = 1;
- oldc = c;
+ lookup(input, last, c) = 1;
+ last = c;
}
while (getline(&buf, &len, stdin) != -1) {
if (buf[0] == '\n')
continue;
- lookup(template, buf[0], buf[1]) = buf[6];
+ template[ntemplate++] = (struct template)
+ {.x1=buf[0], .x2=buf[1], .ins=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;
- }
- }
+ for (int i = 0; i<ntemplate; i++) {
+ struct template t = template[i];
+ unsigned long freq = lookup(input, t.x1, t.x2);
+ lookup(newinput, t.x1, t.ins) += freq;
+ lookup(newinput, t.ins, t.x2) += freq;
}
unsigned long *t = newinput;
newinput = input;
}
}
freq[first-'A']++;
- freq[oldc-'A']++;
+ freq[last-'A']++;
unsigned long min = ULONG_MAX, max = 0;
for (int i = 0; i<26; i++) {