#!/usr/bin/perl -w

use v5.30;
use strict;

my @tree = split /\s+/, <>;

use List::Util qw(sum);

sub walk {
	my $subnodes = shift @tree;
	my $metadata = shift @tree;
	my $sum = 0;
	say "walk $subnodes $metadata";
	my $sn1 = $subnodes;
	my @subvals;
	while ($sn1--) {
		push @subvals, walk();
	}
	if ($subnodes) {
		while ($metadata--) {
			my $id = shift @tree;
			$id--;
			$sum += $subvals[$id]
				if $id < @subvals;
		}
	} else {
		while ($metadata--) {
			$sum += shift @tree;
		}
	}
	say "returning $sum";
	$sum;
}
say walk();
