POJ 3041 Asteroids(最小点覆盖)

POJ 3041 Asteroids

题目链接

题意:一个棋盘上面放东西,要求选择最少的行列能清掉这些东西

思路:很经典的水题,行列有东西的建边,然后最小点覆盖就答案,最小点覆盖等于最大匹配

代码:

#include 
#include 
#include 
#include 
using namespace std;

const int N = 505;

int n, m;
vector g[N];
int left[N], vis[N];

bool dfs(int u) {
	for (int i = 0; i < g[u].size(); i++) {
		int v = g[u][i];
		if (vis[v]) continue;
		vis[v] = 1;
		if (!left[v] || dfs(left[v])) {
			left[v] = u;
			return true;
		}
	}
	return false;
}

int hungary() {
	int ans = 0;
	memset(left, 0, sizeof(left));
	for (int i = 1; i <= n; i++) {
		memset(vis, 0, sizeof(vis));
		if (dfs(i)) ans++;
	}
	return ans;
}

int main() {
	while (~scanf("%d%d", &n, &m)) {
		int x, y;
		for (int i = 1; i <= n; i++) g[i].clear();
		while (m--) {
			scanf("%d%d", &x, &y);
			g[x].push_back(y);
		}
		printf("%d\n", hungary());
	}
	return 0;
}


你可能感兴趣的:(图论-二分图匹配)