<?php
class
EdgeArc {
private
$begin
;
private
$end
;
private
$weight
;
public
function
EdgeArc(
$begin
,
$end
,
$weight
) {
$this
->begin =
$begin
;
$this
->
end
=
$end
;
$this
->weight =
$weight
;
}
public
function
getBegin() {
return
$this
->begin;
}
public
function
getEnd() {
return
$this
->
end
;
}
public
function
getWeight() {
return
$this
->weight;
}
}
class
Edge {
private
$vexs
;
private
$arc
;
private
$arcData
;
private
$krus
;
public
function
Edge(
$vexsData
,
$arcData
) {
$this
->vexs =
$vexsData
;
$this
->arcData =
$arcData
;
$this
->createArc();
}
private
function
createArc() {
foreach
(
$this
->arcData
as
$key
=>
$value
) {
$key
=
str_split
(
$key
);
$this
->arc[] =
new
EdgeArc(
$key
[0],
$key
[1],
$value
);
}
}
public
function
sortArc() {
$this
->quicklySort(0,
count
(
$this
->arc) - 1,
$this
->arc);
return
$this
->arc;
}
private
function
quicklySort(
$begin
,
$end
, &
$item
) {
if
(
$begin
< 0(
$begin
>=
$end
))
return
;
$key
=
$this
->excuteSort(
$begin
,
$end
,
$item
);
$this
->quicklySort(0,
$key
- 1,
$item
);
$this
->quicklySort(
$key
+ 1,
$end
,
$item
);
}
private
function
excuteSort(
$begin
,
$end
, &
$item
) {
$key
=
$item
[
$begin
];
$left
=
array
();
$right
=
array
();
for
(
$i
= (
$begin
+ 1);
$i
<=
$end
;
$i
++) {
if
(
$item
[
$i
]->getWeight() <=
$key
->getWeight()) {
$left
[] =
$item
[
$i
];
}
else
{
$right
[] =
$item
[
$i
];
}
}
$return
=
$this
->unio(
$left
,
$right
,
$key
);
$k
= 0;
for
(
$i
=
$begin
;
$i
<=
$end
;
$i
++) {
$item
[
$i
] =
$return
[
$k
];
$k
++;
}
return
$begin
+
count
(
$left
);
}
private
function
unio(
$left
,
$right
,
$key
) {
return
array_merge
(
$left
,
array
(
$key
) ,
$right
);
}
public
function
kruscal() {
$this
->krus =
array
();
$this
->sortArc();
foreach
(
$this
->vexs
as
$value
) {
$this
->krus[
$value
] =
"0"
;
}
foreach
(
$this
->arc
as
$key
=>
$value
) {
$begin
=
$this
->findRoot(
$value
->getBegin());
$end
=
$this
->findRoot(
$value
->getEnd());
if
(
$begin
!=
$end
) {
$this
->krus[
$begin
] =
$end
;
echo
$value
->getBegin() .
"-"
.
$value
->getEnd() .
":"
.
$value
->getWeight() .
"\n"
;
}
}
}
private
function
findRoot(
$node
) {
while
(
$this
->krus[
$node
] !=
"0"
) {
$node
=
$this
->krus[
$node
];
}
return
$node
;
}
}
?>