#!/usr/bin/perl -w

use v5.16;
use strict;

my %rules;
my %persons;

while (<>) {
	my ($p1, $sign, $score, $p2) = /(\w+) would (\w+) (\d+) happiness units? by sitting next to (\w+)\./;
	$sign = ($sign eq 'gain') ? 1 : -1;
	$rules{$p1}{$p2} = $sign * $score;
	$persons{$p1}++;
	$persons{$p2}++;
}

my $max;
sub perm {
	my ($done, $rest) = @_;

	if (@$rest) {
		for my $i (0 .. $#$rest) {
			my @nd = @$done;
			my @nr = @$rest;
			push @nd, splice @nr, $i, 1;
			perm(\@nd, \@nr);
		}
	} else {
		my $score;
		for my $i (0 .. $#$done) {
			my $self = $done->[$i];
			my @neigh = ($done->[$i-1], $done->[$i == $#$done ? 0 : $i+1]);
			for my $n (@neigh) {
				$score += $rules{$self}{$n};
			}
		}
		$max = $score if !defined $max || $max < $score;	
	}
}

perm([], [ keys %persons ]);
say $max;

