POJ 3041 Asteroids(匈牙利算法模板)

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 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).

Source

USACO 2005 November Gold


/*
     题目大意:给定M个小行星的坐标,每使用一次武器就可以消灭整行或整列的小行星,问最少需要使用多少次武器才可以将全部的小行星消灭。

     思路:给一个二分图匈牙利算法写的很棒的博客http://blog.csdn.net/dark_scope/article/details/8880547 具体思路是将所有小行星的横坐标作为一个点集,竖坐标作为一个点集,那么就可以将这个题目转化为一个最小点覆盖问题,又因为最小点数=最大匹配数,所以最终转化为求此二分图的最大匹配。
*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int INF = 0x3f3f3f3f;
const int M = 560;

bool Map[M][M],vis[M];
int n,m,dis[M];

bool f(int s)
{
    for(int j=1;j<=n;j++)//扫描每一个竖坐标点集
    {
        if(Map[s][j] && !vis[j])//如果没有被标记过并且和s有连线 
        {
            vis[j] = true;
            if(!dis[j] || f(dis[j])) //判断j是否已经和其他的横坐标点集相连
            {
                dis[j] = s;
                return true;
            }
        }
    }
    return false;
}

int main()
{
    int u,v,sum;
    while(~scanf("%d %d",&n,&m))
    {
        memset(Map,false,sizeof(Map));//存图数组
        memset(dis,0,sizeof(dis));
        for(int i=0;i



你可能感兴趣的:(二分图)