動態規劃(最長公共子序列LCS)

Lance發表於2020-11-17

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 協議》,轉載必須註明作者和本文連結

相關文章