我在大约3年前在C中编写了Matrix Chained Multiplication算法,我刚开始学习PHP。
这是C中的算法:
#include<stdio.h>
#include<limits.h>
int MatrixChainOrder(int p[], int n)
{
int m[n][n];
int i, j, k, L, q;
for (i = 1; i < n; i++)
m[i][i] = 0;
// L is chain length.
for (L=2; L<n; L++)
{
for (i=1; i<=n-L+1; i++)
{
j = i+L-1;
m[i][j] = INT_MAX;
for (k=i; k<=j-1; k++)
{
// q = cost/scalar multiplications
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
m[i][j] = q;
}
}
}
return m[1][n-1];
}
int main()
{
int arr[] = {1, 2, 3, 4};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ",
MatrixChainOrder(arr, size));
getchar();
return 0;
}
我是php的新手,我想帮助我将此算法转换为php。
感谢。
答案 0 :(得分:1)
PHP
语法基于C
,类似于后者。
检查出来:
function MatrixChainOrder($p, $n) {
$m = array();
for ($i = 1; $i < $n; $i++)
$m[$i][$i] = 0;
// L is chain length.
for ($L=2; $L < $n; $L++) {
for ($i=1; $i <= $n-$L+1; $i++)
{
$j = $i+$L-1;
$m[$i][$j] = PHP_INT_MAX;
for ($k=$i; $k <= $j-1; $k++)
{
// q = cost/scalar multiplications
$q = $m[$i][$k] + $m[$k+1][$j] + $p[$i-1]* $p[$k]* $p[$j];
if ($q < $m[$i][$j])
$m[$i][$j] = $q;
}
}
}
return $m[1][$n-1];
}
$arr = array(1, 2, 3, 4);
$size = count($arr);
printf("Minimum number of multiplications is %d ", MatrixChainOrder($arr, $size));
答案 1 :(得分:-1)
快速翻拍:)
function matrixChainOrder($p, $n) {
for ($i = 1; $i < $n; $i++)
$m[$i][$i] = 0;
for ($L = 2; $L < $n; $L++)
{
for ($i = 1; $i <= $n - $L + 1; $i++)
{
$j = $i + $L - 1;
$m[$i][$j] = PHP_INT_MAX;
for ($k = $i; $k <= $j - 1; $k++)
{
// $q = cost/scalar multiplications
$q = @$m[$i][$k] + @$m[$k + 1][$j] + @$p[$i - 1] * @$p[$k] * @$p[$j];
if ($q < $m[$i][$j])
$m[$i][$j] = $q;
}
}
}
return $m[1][$n-1];
}
$arr = array(1, 2, 3, 4);
$size = count($arr)/count($arr[0]);
echo "Minimum number of multiplications is ".matrixChainOrder($arr, $size);