1. 程式人生 > >【二分圖】【找最大流、最小獨立集、匈牙利演算法】

【二分圖】【找最大流、最小獨立集、匈牙利演算法】

                                   Asteroids Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 <= N <= 500). The grid contains K asteroids (1 <= K <= 10,000), which are conveniently located at the lattice points of the grid. 

Fortunately, Bessie has a powerful weapon that can vaporize all the asteroids in any given row or column of the grid with a single shot.This weapon is quite expensive, so she wishes to use it sparingly.Given the location of all the asteroids in the field, find the minimum number of shots Bessie needs to fire to eliminate all of the asteroids.

Input

* Line 1: Two integers N and K, separated by a single space. 
* Lines 2..K+1: Each line contains two space-separated integers R and C (1 <= R, C <= N) denoting the row and column coordinates of an asteroid, respectively.

Output

* Line 1: The integer representing the minimum number of times Bessie must shoot.

Sample Input

3 4
1 1
1 3
2 2
3 2

Sample Output

2

Hint

INPUT DETAILS: 
The following diagram represents the data, where "X" is an asteroid and "." is empty space: 
X.X 
.X. 
.X.
 

OUTPUT DETAILS: 
Bessie may fire across row 1 to destroy the asteroids at (1,1) and (1,3), and then she may fire down column 2 to destroy the asteroids at (2,2) and (3,2).

題意可以概括為:
給一個map,上面的X代表需要覆蓋的位置,每次只能覆蓋一行或一列,問最少需要執行幾次覆蓋操作。

二分圖之所以靈活,是因為有很多看似無關的問題都能轉化到最大匹配的問題上來。

問題一:最小覆蓋,尋找一個點集,使得圖中每一條邊至少有一個點在該點集中,且該點集所包含的點數最少。(最小覆蓋的情況下,每邊條有且僅有一個端點在該點集中)。

定理:二分圖最小覆蓋等於二分圖的最大匹配。

證明:設最大匹配數為m。

1:至少要m個點

證:因為二分圖的最大匹配數為m,而每條邊的端點互不相同,故至少要有m個點,才可以覆蓋到所有的邊。

2:最多要m個點

證:若存在m+1個點,則必有一條邊的兩個端點在該點集中,刪去其中一點仍可以保持每條邊被覆蓋到,以此類推,大於m個點的點集都不是最小覆蓋。

綜上:最小覆蓋的點集所包含的點數等於m,即二分圖的最小覆蓋等於二分圖的最大匹配。

經典問題:PKU3041 Asteroids,給定一個矩陣,矩陣上有若干個障礙物,你可以一次清除一行或者一列的障礙物,問最少的清除操作需要幾步。