from collections import deque
from functools import cache
from sys import stdin


def main():
    rates = {}
    tunnels = {}

    for line in stdin:
        a, b = line.split(";")
        a, rate = a.split("=")
        position = a.split()[1]
        rates[position] = int(rate)
        tunnels[position] = b.replace(",", " ").split()[4:]

    @cache
    def get_distance(a, b):
        queue = deque([(0, a)])
        visited = set()

        while queue:
            distance, position = queue.popleft()

            if position in visited:
                continue

            visited.add(position)

            if position == b:
                return distance

            for new_position in tunnels[position]:
                queue.append((distance + 1, new_position))

    @cache
    def open_valve(valves, position):
        valves = list(valves)
        valves.remove(position)
        return tuple(valves)

    @cache
    def solve(time, position, valves, helpers):
        result = 0

        for new_position in valves:
            new_time = time - get_distance(position, new_position) - 1

            if new_time <= 0:
                continue

            result = max(
                result,
                rates[new_position] * new_time
                + solve(
                    new_time, new_position, open_valve(valves, new_position), helpers
                ),
            )

        if helpers:
            result = max(result, solve(helpers[0], "AA", valves, helpers[1:]))

        return result

    good_valves = {position for position, rate in rates.items() if rate}

    for helper_count in range(2):
        time = 30
        helpers = []

        for _ in range(helper_count):
            time -= 4
            helpers.append(time)

        print(solve(time, "AA", tuple(sorted(good_valves)), tuple(helpers)))


if __name__ == "__main__":
    main()
