-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnionFind.php
50 lines (39 loc) · 861 Bytes
/
UnionFind.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
<?php
class UnionFind
{
private $id = [];
private $count;
public function __construct(int $N)
{
$this->count = $N;
for ($i = 0; $i < $N; $i++) {
$this->id[$i] = $i;
}
}
public function count(): int
{
return $this->count;
}
public function connected(int $p, int $q): bool
{
return $this->find($p) == $this->find($q);
}
public function find(int $p): int
{
return $this->id[$p];
}
public function union(int $p, int $q)
{
$pID = $this->find($p);
$qID = $this->find($q);
if ($pID == $qID) return;
for ($i = 0; $i< count($this->id); $i++)
{
if ($this->id[$i] == $pID) $this->id[$i] == $qID;
}
$this->count--;
}
}
$n = 625;
$uf = new UnionFind($n);
//while (!)