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 <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
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<m;i++)
        {
            scanf("%d %d",&u,&v);
            Map[u][v] = true;//标记
        }
        sum = 0;
        for(int i=1;i<=n;i++)
        {
            memset(vis,false,sizeof(vis));//清空标记数组
            if(f(i))
            {
                sum++;
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值