[Usaco2005 Nov]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

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

Sample Output
2

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


二分图匹配,对于每个点,它若被行清理过,就不必再次被列清理,反之亦然,然后就是最大匹配

/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline int read(){
	int x=0,f=1;char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x>=10)     print(x/10);
	putchar(x%10+'0');
}
const int N=5e2;
int path[N+10],pre[N*N+10],now[N+10],child[N*N+10];
int tot,n,m;
bool use[N+10];
void join(int x,int y){pre[++tot]=now[x],now[x]=tot,child[tot]=y;}
bool check(int x){
    for (int p=now[x],son=child[p];p;p=pre[p],son=child[p]){
        if (use[son])   continue;
        use[son]=1;
        if (path[son]<0||check(path[son])){path[son]=x;return 1;}
    }
    return 0;
}
void work(){
    memset(path,-1,sizeof(path));
    int res=0;
    for (int i=1;i<=n;i++){
        memset(use,0,sizeof(use));
        if (check(i))   res++;
    }
    printf("%d\n",res);
}
int main(){
    n=read(),m=read();
    for (int i=1;i<=m;i++){
        int x=read(),y=read();
        join(x,y);
    }
    work();
    return 0;
}
posted @ 2018-02-06 14:03  Wolfycz  阅读(231)  评论(0编辑  收藏  举报