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。
并不会建图,听了同学的想法- -。
横着标记,例如样例就是
1 1
2
3
竖着标记就是
1 3
2
2
然后对于同一个格子内的两个数字连接起来,就成了一个二分图,找到其最大匹配,就是答案了。
至于原理……其实看了二分匹配之后的结果,就会发现,每个格子都被一条线连着,这就表示都是被扫过的,而边数又是最少的,所以这一定是最优答案。
二分匹配就可以使用匈牙利算法,网上找了一发,就是代码中的find函数,涉及到leap连接,vis访问数组,g匹配数组。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
int a[505][505], l[505][505], rig[505][505], leap[505][505], g[505], vis[505];
int numl, numr;
bool find(int x)
{
int i, j;
for (j = 1; j <= numr; j++){
if (leap[x][j] && !vis[j]){
vis[j] = 1;
if (g[j] == 0 || find(g[j])){
g[j] = x;
return true;
}
}
}
return false;
}
int main()
{
int i, j, m, n, ans, t, r, c;
while (scanf("%d%d", &r, &c) != EOF)
{
memset(a, 0, sizeof(a));
int x, y;
for (i = 1; i <= c; i++){
cin >> x >> y;
a[x][y] = 1;
}
memset(l, 0, sizeof(l));
memset(rig, 0, sizeof(rig));
memset(leap, 0, sizeof(leap));
int cnt = 1, flag;
for (i = 1; i <= r; i++){
flag = 0;
for (j = 1; j <= r; j++){
if (a[i][j]){
l[i][j] = cnt;flag = 1;
}
}
numl = cnt;
if (flag)cnt++;
}
cnt = 1;
for (j = 1; j <= r; j++){
flag = 0;
for (i = 1; i <=r; i++){
if (a[i][j]){
rig[i][j] = cnt; flag = 1;
}
}
numr = cnt;
if (flag)cnt++;
}
for (i = 1; i <= r; i++){
for (j = 1; j <= r; j++){
if (l[i][j] && rig[i][j]){
leap[l[i][j]][rig[i][j]] = 1;
}
}
}
ans = 0;
memset(g, 0, sizeof(g));
for (i = 1; i <= numl; i++)
{
memset(vis, 0, sizeof(vis));
if (find(i))ans++;
}
cout << ans << endl;
}
return 0;
}