POJ 2594 Treasure Exploration(最小路径覆盖变形)

POJ 2594 Treasure Exploration

题目链接

题意:有向无环图,求最少多少条路径能够覆盖整个图,点能够反复走

思路:和普通的最小路径覆盖不同的是,点能够反复走,那么事实上仅仅要在多一步。利用floyd求出传递闭包。然后依据这个新的图去做最小路径覆盖就可以

代码:

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int N = 505;

int n, m, g[N][N];

int left[N], vis[N];

bool dfs(int u) {
	for (int i = 1; i <= n; i++) {
		if (g[u][i] && !vis[i]) {
			vis[i] = 1;
			if (!left[i] || dfs(left[i])) {
				left[i] = 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) && n) {
		int u, v;
		memset(g, 0, sizeof(g));
		while (m--) {
			scanf("%d%d", &u, &v);
			g[u][v] = 1;
		}
		for (int k = 1; k <= n; k++) {
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					g[i][j] |= (g[i][k]&g[k][j]);
				}
			}
		}
		printf("%d\n", n - hungary());
	}
	return 0;
}


你可能感兴趣的:(POJ 2594 Treasure Exploration(最小路径覆盖变形))