for ($i = 0; $i < $n; $i++) {
    fscanf(STDIN, "%s %s", $node1, $node2);
    //$node1 = $t[$i][0];
    //$node2 = $t[$i][1];
    if (!isset($TREE[$node1])) {
        $TREE[$node1] = array('nodes' => array($node2), 'total' => 0, 'flag' => 0);
    } else {
        $TREE[$node1]['nodes'][] = $node2;
    }
    if (!isset($TREE[$node2])) {
        $TREE[$node2] = array('nodes' => array(), 'total' => 0, 'flag' => 0);
    }
}
error_log(var_export($TREE, true));
error_log(var_export('---------', true));
echo gextri($TREE) + 1;
echo "\n";
# ====================================================================
function gextri($TREE)
{
    while (!checkedAllNodes($TREE)) {
        $i = startnode($TREE);
        recursewalk($TREE, $i);
    }
    return searchMax($TREE);
}
function checkedAllNodes(&$TREE)
{
    foreach ($TREE as $N) {
        if (!$N['flag']) {
            return 0;
<?php

$timestart = microtime(1);
fscanf(STDIN, "%d", $N);
$ROOMS = array();
for ($i = 0; $i < $N; $i++) {
    $room = stream_get_line(STDIN, 256, "\n");
    $room = explode(' ', $room);
    $ROOMS[$room[0]] = array('cost' => $room[1], '0' => $room[2], '1' => $room[3], 'total' => 0);
}
$ROOMS['E']['total'] = 0;
$ROOMS['E']['cost'] = 0;
$ROOMS[0]['total'] = $ROOMS[0]['cost'];
error_log(var_export('filling array - ' . (microtime(1) - $timestart), true));
echo gextri($ROOMS) . "\n";
error_log(var_export('total - ' . (microtime(1) - $timestart), true));
/*
// Write an action using echo(). DON'T FORGET THE TRAILING \n
// To debug (equivalent to var_dump): error_log(var_export($var, true));
*/
# ====================================================================
function gextri($ROOMS)
{
    $timestart = microtime(1);
    $cnt = count($ROOMS) - 1;
    for ($i = 0; $i < $cnt; $i++) {
        $r = $ROOMS[$i][0];
        $ROOMS[$r]['total'] = calcCost($ROOMS, $i, 0);
        $r = $ROOMS[$i][1];
        $ROOMS[$r]['total'] = calcCost($ROOMS, $i, 1);
    }