[BZOJ1693]&&[Usaco2007 Demo] 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.

输入格式 InputFormat

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.

输出格式 OutputFormat

Line 1: The integer representing the minimum number of times Bessie must shoot.

样例输入 SampleInput

5 16
1 1
1 2
1 3
1 4
1 5
2 1
2 5
3 1
3 5
4 1
4 5
5 1
5 2
5 3
5 4
5 5

样例输出 SampleOutput

4


BZOJ 1693


行列坐标建二分图,最小点覆盖。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=505;
int i,j,t,n,m,l,r,k,z,y,x;
struct edge
{
    int to,nx;
}e[maxn*maxn];
int head[maxn*maxn],match[maxn*maxn],used[maxn*maxn];
int mat,cnt,sum;
bool b[maxn];
inline void ins(int u,int v)
{
    e[++cnt].to=v;e[cnt].nx=head[u];
    head[u]=cnt;
}
bool crosspath(int s,int now)
{
    int i,v;
    for (i=head[s];i;i=e[i].nx)
    {
        v=e[i].to;
        if (used[v]!=now)
        {
            used[v]=now;
            if (!match[v] || crosspath(match[v],now))
            {
                match[v]=s;
                return true;
            }
        }
    }
    return false;
}
inline void hungary()
{
    int i;
    memset(match,false,sizeof(match));
    memset(used,0,sizeof(used));
    for (i=1;i<=n;i++) if (b[i])
    {
        if (crosspath(i,i)) mat++;
    }
}
int main()
{
    memset(head,0,sizeof(head));
    memset(b,false,sizeof(b));
    mat=cnt=0;
    scanf("%d%d",&n,&k);
    for (i=1;i<=k;i++) scanf("%d%d",&x,&y),ins(x,y+n),b[x]=true;
    hungary();
    printf("%d\n",mat);
    return 0;
}