POJ3041 最小点覆盖 最大匹配数 回顾匈牙利算法

来源:互联网 发布:淘宝装修助手破解版 编辑:程序博客网 时间:2024/05/16 09:56

Description

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 41 11 32 23 2

Sample Output

2



这道题就是求最小点覆盖,而最小点覆盖=最大匹配数,这道题我已经做了五遍了,每次都是对匈牙利算法的一个回顾,这是一道非常经典的题目。

匈牙利算法求最小点覆盖,也就是最大匹配数的算法流程如下:

for(int i=1;i<=xNum;i++){for(int j=1;j<=yNum;j++){ifVisited[j]=false''}if(dfs(i)==true){number++;}}bool dfs(int i){for(int j=1;j<=yNum;j++){if(ifVisited[j]==false&&grid[i][j]==true){ifVisited[j]==true;if(ancestor[j]==0||dfs(ancestor[j])==true){ancestor[j]=i;return true;}}}return false;}


其中,number为最大匹配数,ancestor为某个y点所链接的前驱x点。


本题的做法就类似于上面写的这个算法,做好输入输出后就可以写了,代码未测试,只是作为练手之用。

#include<iostream>using namespace std;int xNum,yNum,ancestor[1000],n,k;bool grid[1000][1000];bool ifVisited[1000];bool dfs(int i){for(int j=1;j<=yNum;j++){if(ifVisited[j]==false&&grid[i][j]==true){ifVisited[j]==true;if(ancestor[j]==0||dfs(ancestor[j])==true){ancestor[j]=i;return true;}}}return false;}int main(){cin>>n>>k;for(int i=1;i<=n;i++){for(int j=1;j<=n;j++)grid[i][j]==false;} for(int i=1;i<=k;i++){int a,b;cin>>a>>b;grid[a][b]=true;}xNum=yNum=n;for(int i=1;i<=xNum;i++){for(int j=1;j<=yNum;j++){ifVisited[j]=false;}if(dfs(i)==true){number++;}}cout<<number;return 0;}



0 0
原创粉丝点击