http://poj.org/problem?id=3041
Asteroids
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 28941 | Accepted: 15524 |
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).
题意就是坐标上有一些点,你每次只能清除一行或一列,问你最少多少次,可以将点全部清完。
感觉这个题很像学最大匹配的时候给的例题,当时是一个棋盘上有很多点,删去多少点使得每行每列都只有一个点。那个题的解法是x坐标为一个点集X,y坐标为一个点集Y,有一个点(x,y),就在x与y连一条边。每行每列都只有一个点,即相当于X点集中x只能连一条边(或Y点集中y只能连一条边)。就转换成了最大匹配问题。
至于本题,我们也把坐标上的一个点(x,y)当成X点集中x与Y点集中y之间有一条边。我们需要删去所有坐标上的点,等于覆盖所有X点集与Y点集之间的边。每次删去一行(或一列),就相当于选中X点集(或Y点集)中一个点,同时覆盖所有与x(或y)相连的边。就是二分图的最小点覆盖问题,就是最少的点覆盖所有的边。
二分图的最小点覆盖=最大匹配数。
证明不再给出。(因为我自己也没有看懂网上的讲解)
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstring>
using namespace std;
const int N=1010;
int m,n,k;//e边数,m,n分别为两个点集中点的数量
int line[N][N];//map用来存边
bool used[N];//在回溯过程中是否已被配对
int ans[N];//最后连接的点
bool found(int x)
{
for(int i=1;i<=n;i++)
if(line[x][i]&&!used[i])
{
used[i]=1;
if(!ans[i]||found(ans[i]))
{
ans[i]=x;
return 1;
}
}
return 0;
}
int main()
{
while(~scanf("%d%d",&n,&k))
{
int x,y;
memset(line,0,sizeof(line));
memset(ans,0,sizeof(ans));
for(int i=0;i<k;i++)
{
scanf("%d%d",&x,&y);
line[x][y]=1;
}
int cnt=0;
for(int i=1;i<=n;i++)
{
memset(used,0,sizeof(used));
if(found(i))
cnt++;
}
printf("%d\n",cnt);
}
}