<?php
class Edge
{
public $v1;
public $v2;
public $weight;
function Edge($v1, $v2, $weight)
{
$this->v1 = $v1;
$this->v2 = $v2;
$this->weight = $weight;
}
}
class Vertex
{
public $nRank;
public $vRoot;
public $name;
function Vertex($name)
{
$this->name = $name;
$this->nRank = 0;
$this->vRoot = $this;
}
function GetRoot()
{
if ($this->vRoot != $this)
$this->vRoot = $this->vRoot->GetRoot();
return $this->vRoot;
}
}
class Kruskal
{
var $all_vertex = array();
var $all_edge = array();
function create()
{
//create
}
function edge_sort()
{
function cmp($a, $b)
{
if ($a->weight == $b->weight)
return 0;
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($this->all_edge, "cmp");
}
function Join(Vertex $vRoot1, Vertex $vRoot2)
{
if ($vRoot2->nRank < $vRoot1->nRank)
$vRoot2->vRoot = $vRoot1;
else {
$vRoot1->vRoot = $vRoot2;
if ($vRoot1->nRank == $vRoot2->nRank)
$vRoot1->nRank++;
}
}
function mst_create()
{
$mst_vertex = array();
$this->edge_sort();
for ($i=0;$i<count($this->all_edge);$i++) {
$v1 = $this->all_edge[$i]->v1->GetRoot();
$v2 = $this->all_edge[$i]->v2->GetRoot();
if($v1->name==$v2->name)
continue;
$this->Join($v1, $v2);
array_push($mst_vertex, $this->all_edge[$i]);
}
return $mst_vertex;
}
}
Minimum spanning tree用PHP寫
張貼者:
matttt
on 2011年5月15日
標籤:
PHP
0 意見:
張貼留言