Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 求复数组的最大路径_Php - Fatal编程技术网

Php 求复数组的最大路径

Php 求复数组的最大路径,php,Php,我有一个数组: $data = array( 1 => array( "time" => 1, "parent" => array(4) ), 2 => array( "time" => 3, "parent" => array(4, 5) ), 3 => array( "time" => 2, "parent" => array(6) ), 4 => arra

我有一个数组:

$data = array(
  1 => array(
    "time" => 1,
    "parent" => array(4)
  ),
  2 => array(
    "time" => 3,
    "parent" => array(4, 5)
  ),
  3 => array(
    "time" => 2,
    "parent" => array(6)
  ),
  4 => array(
    "time" => 1,
    "parent" => array(6)
  ),
  5 => array(
    "time" => 1,
    "parent" => array(4)
  ),
  6 => array(
    "time" => 1,
    "parent" => array()
  )
);
Key是元素的ID,parent是元素的数组,它引用元素ID,time只是一个整数

这是给定阵列的示例:

左下角的整数是“ID”,中间的整数是“时间”。

我的目标是找到这个数组中最耗时的路径。在给定的示例中,路径将是2->5->4->6(id方向),结果总共是6个“时间”。这在纸上看起来很简单,但是我似乎无法真正编写算法来获取最耗时路径的元素。我将感谢任何帮助

我认为算法应该是蛮力的,检查所有可用的选项。因此,对于给定的数组,它将如下所示:

1 -> 4 -> 6 = 3
2 -> 4 -> 6 = 5
2 -> 5 -> 4 -> 6 = 6 
3 -> 6 = 3
4 -> 6 = 2
5 -> 4 -> 6 = 3

提前感谢。

请注意,只有在阵列中没有循环时,此操作才有效

// Note: built this in the SO editor, might have bugs
$cached = [];
$arrays = []; // Do this yourself

function get_path($num) {
    global $arrays, $cached;
    if (isset($cached[$num])) return $cached[$num];

    $array = $arrays[$num];
    $maxtime = $array['time'];
    $bestpath = array($num);
    foreach ($array['parent'] as $i) {
        $path = get_path($i);
        if ($path['time']+$array['time'] > $maxtime) {
            $maxtime = $path['time'] + $array['time'];
            $bestpath = array_merge(array($num),$path['path']);
        }
    }

    $cached[$num] = array('path' => $bestpath, 'time' => $maxtime);
    return $cached[$num];
}

var_dump(get_path(5));
不是真正的暴力方式,应该足够接近
O(n)
。基本思想是,您只需缓存它可以采用的路径


注意:我在这里使用了一些C风格的语法,但理想情况下,您不会像这样编写代码

您已经尝试了什么?您从哪里获得了这个数组?我尝试了各种方法,但似乎无法使其工作。此数组只是一个缩小的var_dump(),使用递归函数获取已添加内容的列表并查找“剩余内容的最大值”。然后使用该值进行添加,并再次调用自身,直到没有剩余值为止。返回最大值并从下一个初始值开始。@Tom为什么会出现这种情况
2->5->4->6=6
,我会认为这就像
2->5->6=4
,否则
2->4->6=5
为什么不像
2->4->5->6=5
?(如果我不看图片的话)