动态规划(最长公共子序列LCS)

Laravel

<?php
class longest_common_subsequence
{
    public function __construct($x, $y, $m, $n, &$c, &$b)
    {
        for($i = 0; $i <= $m; $i++)
        {
            $c[$i][0] = 0;
        }
        for($j = 1; $j <= $n; $j++)
        {
            $c[0][$j] = 0;
        }
        for($i = 1; $i<= $m; $i++)
        {
            for($j = 1; $j <= $n; $j++)
            {
                if($x[$i-1] == $y[$j-1])
                {
                    $c[$i][$j] = $c[$i-1][$j-1] + 1;
                    $b[$i][$j] = 0;
                }
                else if($c[$i-1][$j] >= $c[$i][$j-1])
                {
                    $c[$i][$j] = $c[$i-1][$j];
                    $b[$i][$j] = 1;
                }
                else
                {
                    $c[$i][$j] = $c[$i][$j-1];
                    $b[$i][$j] = -1;
                }
            }
        }
        echo iconv('utf-8', 'gbk', "以上两个字符串的最长公共子序列为:\n");
        $this->output($b, $x, $m, $n);
        echo "\n";
    }

    private function output($b, $x, $i, $j)
    {
        if($i == 0 || $j == 0)
        {
            return;
        }
        if($b[$i][$j] == 0)
        {
            $this->output($b, $x, $i-1, $j-1);
            echo $x[$i-1];
        }
        else if($b[$i][$j] == 1)
        {
            $this->output($b, $x, $i-1, $j);
        }
        else
        {
            $this->output($b, $x, $i, $j-1);
        }
    }
}

function read()
{
    $input = trim(fgets(STDIN));
    return $input;
}

function test()
{
    $x = 'ABCBDAB';
    $y = 'BDCABA';
    $b = array();
    $c = array();

    $m = strlen($x);
    $n = strlen($y);

    new longest_common_subsequence($x, $y, $m, $n, $c, $b);

    return 0;
}

function main()
{
    echo iconv('utf-8', 'gbk', "请输入第一个字符串:\n");
        $x = read();
        echo iconv('utf-8', 'gbk', "请输入第二个字符串:\n");
    $y = read();
    $b = array();
    $c = array();

    $m = strlen($x);
    $n = strlen($y);

    new longest_common_subsequence($x, $y, $m, $n, $c, $b);

    return 0;
}

if(!empty($argv[1]) && $argv[1]=='test')
{
    test();    
}
else
{
    main();
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!