#!/usr/bin/perl

use v5.30;
use strict;

my %all;
my %above;
my %top;

while (<>) {
	my ($name, $num, $rest) = /^(\w+) \((\d+)\)(.*)/;
	$all{$name} = $num;
	next if !length $rest;
	for my $t ($rest =~ /(\w+)/g) {
		push @{ $above{$name} }, $t;
		$top{$t} = 1;
	}
}

my $start = 'uownj';

sub walk {
	my ($node) = @_;
	my %sizes;
	return $all{$node}
		if !exists $above{$node};

	my $sum;
	my %nodes;
	for my $ab (@{ $above{$node} }) {
		my $s = walk($ab);
		$sum += $s;
		$sizes{$s}++;
		$nodes{$s} = $ab;
	}
	my @sizes = sort { $sizes{$a} <=> $sizes{$b} } keys %sizes;
	if (@sizes == 1) {
		return $sum + $all{$node};
	} else {
		say $all{$nodes{$sizes[0]}} + $sizes[1]-$sizes[0];
		exit 0;
	}
}

walk('uownj');



