<?php

[$template, $rules] = explode("\n\n", file_get_contents('./input.txt'));

$template = str_split($template);

$pair_insertion_rules = [];
foreach (explode("\n", $rules) as $rule) {
    [$key, $value] = explode(' -> ', $rule);
    $pair_insertion_rules[$key] = $value;
}

$pair_counts = count_pairs($template);

for ($i = 0; $i < 40; $i++) {
    $new_pair_counts = $pair_counts;
    foreach ($pair_counts as $key => $value) {
        $substitute = $pair_insertion_rules[$key];
        $pair1 = $key[0] . $substitute;
        $pair2 = $substitute . $key[1];

        $new_pair_counts[$pair1] = array_key_exists($pair1, $new_pair_counts) ? $new_pair_counts[$pair1] + $value : $value;
        $new_pair_counts[$pair2] = array_key_exists($pair2, $new_pair_counts) ? $new_pair_counts[$pair2] + $value : $value;
        $new_pair_counts[$key] = $new_pair_counts[$key] - $value;
        if ($new_pair_counts[$key] < 1) {
            unset($new_pair_counts[$key]);
        }
    }
    $pair_counts = $new_pair_counts;
}

$count_elements = [];
foreach ($pair_counts as $pair => $pair_count) {
    foreach (str_split($pair) as $element) {
        $count_elements[$element] = array_key_exists($element, $count_elements) ? $count_elements[$element] + $pair_count : $pair_count;
    }
}

array_walk($count_elements, static function (&$count_element) {
    $count_element = ceil($count_element / 2);
});

function count_pairs($template): array
{
    $counts = [];
    for ($i = 0; $i < count($template) - 1; $i++) {
        $pair = $template[$i] . $template[$i + 1];
        $counts[$pair] = array_key_exists($pair, $counts) ? $counts[$pair]+1 : 1;
    }

    return $counts;
}

echo max($count_elements) - min($count_elements);