-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmincut.php
More file actions
52 lines (45 loc) · 1.05 KB
/
mincut.php
File metadata and controls
52 lines (45 loc) · 1.05 KB
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
<?php
$filename='kargerMinCut.txt';
echo '<pre>';
$s = file_get_contents($filename);
$adj = explode("\n",$s);
//srand(0);
foreach ($adj as $key => &$val){
$val = explode("\t",trim($val));
$hash[array_shift($val)]=$val;
}
//print_r($hash);
while (count($hash)>2) {
//pick random (u,v) from remaining
$nodes = array_keys($hash);
$u_pos = array_rand($nodes);
$u = $nodes[$u_pos];
$u = trim($u);
$v_pos = array_rand($hash[$u]);
$v = $hash[$u][$v_pos];
$v = trim($v);
//merge u and v
$merge_u = $hash[$u];
$merge_v = $hash[$v];
$merge_u = array_merge($merge_u,$merge_v);
foreach ($merge_u as $key=>&$value) {
if (trim($value)==$u || trim($value)==$v) unset($merge_u[$key]);
}
$hash[$u]=$merge_u;
unset($hash[$v]);
//replace all cases of v by u in hash
foreach ($hash as $node=>$list) {
foreach ($list as $k=>$vl) {
if (trim($vl)==trim($v)) {
$hash[$node][$k]=$u;
}
}
}
}
//Output the number of edges in first of two remaining nodes.
foreach ($hash as $key=>$value) {
echo 'mincut='.count($value);
break;
}
echo '</pre>';
?>