POJ 3014:Asteroids(二分匹配,匈牙利演算法)

B0B0發表於2019-05-12

Asteroids

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 14399 Accepted: 7836

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

    01.#include<cstdio>  
    02.#include<cstring>  
    03.#include<algorithm>  
    04.#include<iostream>  
    05.  
    06.using namespace std;  
    07.  
    08.const int M = 1000 + 5;  
    09.int n, m;  
    10.int link[M];  
    11.bool MAP[M][M];  
    12.bool cover[M];  
    13.int ans;  
    14.  
    15.void init()  
    16.{  
    17.    int num;  
    18.    int x;  
    19.    int y;  
    20.    memset(MAP, false, sizeof(MAP));  
    21.    for(int i=1; i<=m; i++)  
    22.    {  
    23.            scanf("%d%d", &x, &y);  
    24.            MAP[x][y]=true;  
    25.    }  
    26.  
    27.}  
    28.  
    29.bool dfs(int x)  
    30.{  
    31.    for(int y=1; y<=n; y++)  
    32.    {  
    33.        if(MAP[x][y] && !cover[y])  
    34.        {  
    35.            cover[y]=true;  
    36.            if(link[y]==-1 || dfs(link[y]))  
    37.            {  
    38.                link[y]=x;  
    39.                return true;  
    40.            }  
    41.        }  
    42.    }  
    43.    return false;  
    44.}  
    45.  
    46.int main()  
    47.{  
    48.    while(scanf("%d%d", &n, &m)!=EOF)  
    49.    {  
    50.        ans=0;  
    51.        init();  
    52.        memset(link, -1, sizeof(link));  
    53.        for(int i=1; i<=n; i++)  
    54.        {  
    55.            memset(cover, false, sizeof(cover));  
    56.            if( dfs(i) )  
    57.                ans++;  
    58.        }  
    59.        printf("%d
", ans);  
    60.    }  
    61.  
    62.    return 0;  
    63.}  

相關文章