0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

最大マッチング(PHP)

Last updated at Posted at 2016-12-09
	// maximum matching algorithm
	// unweighted bipartite graph
	// dfs hungarian algorithm

	function dfs($bigraph, $u, &$path, &$matching){
		foreach($bigraph[$u] as $v){
			if(!isset($path[$v])){		// not in path already
				$path[$v] = true;
				if(!isset($matching[$v]) || dfs($bigraph, $matching[$v], $path, $matching)){
					// not matching node, the path is agumenting path, switch path, and return true
					$matching[$v] = $u;
					$matching[$u] = $v;
					return true;
				}
			}
		}
		
		return false; 					// not agumenting path
	}
	
	function hungarian($bigraph){
		$matching = [];

		foreach($bigraph as $u=>$x){
			if(!isset($matching[$u])){	// not a matching node
				$path = []; 			// save the nodes in path
				dfs($bigraph, $u, $path, $matching);
			}
		}
		
		return array_intersect_key($matching, $bigraph);
	}

	// left node idx is key
	// right nodes is value
	// eg. left nodes: 0 - 4, right nodes = 5 - 9
	$bigraph = [0 => [6, 9], 1 => [7], 2 => [6, 8], 3 => [8, 9], 4 => [5, 7]];
	$r = hungarian($bigraph);
	print_r($r);
?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?