首页 > 代码库 > POJ2594-Treasure Exploration(最小路径覆盖变形)

POJ2594-Treasure Exploration(最小路径覆盖变形)

题目链接


题意:在一个有向图上,至少放多少个机器人可以遍历整个图(每个顶点可以重复遍历)?

思路:最小路径覆盖的变形,因为点可以重复遍历,所以要用floyd重新建图,然后用最小路径覆盖去做。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

const int MAXN = 1005;

int g[MAXN][MAXN];
int linker[MAXN];
bool used[MAXN];
int n, m;

bool dfs(int u) {
    for (int v = 1; v <= n; v++) {
        if (g[u][v] && !used[v]) {
            used[v] = true; 
            if (linker[v] == -1 || dfs(linker[v])) {
                linker[v] = u; 
                return true;
            }
        } 
    }
    return false;
}

int hungary() {
    int res = 0;
    memset(linker, -1, sizeof(linker));
    for (int u = 1; u <= n; u++) {
        memset(used, false, sizeof(used)); 
        if (dfs(u)) res++;
    }
    return res;
}

int main() {
    while (scanf("%d%d", &n, &m) && n) {
        memset(g, 0, sizeof(g));
        int u, v;
        for (int i = 0; i < m; i++) {
            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;
}


POJ2594-Treasure Exploration(最小路径覆盖变形)