POJ 3041 (二分图匹配 最小顶点覆盖)

Asteroids
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18793   Accepted: 10204

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

Source

USACO 2005 November Gold

题意是给出m个坐标,有一束激光每次可以水平或竖直地消灭所有的路径上的坐标,求最少的激光次数。

很经典的构图题了。先给每行每列拆成两组点,对于一个坐标(x,y),相当于连一条x到y的边,然后这个二分图的最小定点覆盖就是答案。

最小定点覆盖在二分图里面有多项式时间的解法,就等于最大匹配。

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <vector>
#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
#define maxn 21111
#define maxm 5111111

int n, m;
struct node {
	int u, v, next;
} edge[maxm];
int head[maxn], x[maxn], y[maxn], cnt;

void add_edge (int u, int v) {
	edge[cnt].u = u, edge[cnt].v = v, edge[cnt].next = head[u], head[u] = cnt++;
}

int pre[maxn]; bool vis[maxn];
bool dfs(int u) {
	for (int i = head[u]; i != -1 ;i = edge[i].next) {
		int v = edge[i].v; 
		if(!vis[v]) {
			vis[v] = true;
			if (pre[v] == -1 || dfs(pre[v])) {
				pre[v] = u;
				return true; 
			}
		} 
	}
	return false; 
}

int hungry () {
	int ans = 0;
	memset (pre, -1, sizeof pre);
	for (int i = 1; i <= n; i++) {
		if (pre[i] < 0) {
			memset (vis, 0, sizeof vis);
			if (dfs (i))
				ans++;
		}
	}
	return ans;
}

int main () {
	while (scanf ("%d%d", &n, &m) == 2) {
		cnt = 0;
		memset (head, -1, sizeof head);
		for (int i = 1; i <= m; i++) {
			scanf ("%d%d", &x[i], &y[i]);
			add_edge (x[i], y[i]+n);
		}
		printf ("%d\n", hungry ());
	}
	return 0;
}



你可能感兴趣的:(POJ 3041 (二分图匹配 最小顶点覆盖))