forked from carlfriess/MinSpantree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinSpantree.php
98 lines (64 loc) · 1.81 KB
/
MinSpantree.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
class Vertex {
public $value;
public $parent;
function __construct($value) {
$this->value = $value;
$this->parent = $this;
}
public function getRoot() {
return $this->parent == $this ? $this : $this->parent->getRoot();
}
}
class Edge {
public $u;
public $v;
public $weight = 0;
function __construct($u, $v, $weight) {
$this->u = $u;
$this->v = $v;
$this->weight = $weight;
}
}
class Scanner
{
private $buffer = array();
public function nextInt(){
if (count($this->buffer) <= 0) {
$line = trim(fgets(STDIN));
$this->buffer = preg_split('/\s+/', $line);
}
return array_shift($this->buffer);
}
}
function cmp($a, $b) {
return $a->weight > $b->weight;
}
$scanner = new Scanner();
for ($numTests = $scanner->nextInt(); $numTests > 0; $numTests--) {
$numVertices = $scanner->nextInt();
$numEdges = $scanner->nextInt();
$vertices = array();
$edges = array();
for ($i=0; $i < $numEdges; $i++) {
$uValue = $scanner->nextInt() - 1;
$vValue = $scanner->nextInt() - 1;
if (!array_key_exists($uValue, $vertices)) {
$vertices[$uValue] = new Vertex($uValue);
}
if (!array_key_exists($vValue, $vertices)) {
$vertices[$vValue] = new Vertex($vValue);
}
array_push($edges, new Edge($vertices[$uValue], $vertices[$vValue], $scanner->nextInt()));
}
usort($edges, "cmp");
$totalWeight = 0;
foreach ($edges as $edge) {
if ($edge->u->getRoot() != $edge->v->getRoot()) {
$edge->v->getRoot()->parent = $edge->u->getRoot();
$totalWeight += $edge->weight;
}
}
fwrite(STDOUT, $totalWeight . "\n");
}
?>