以下是实现这一算法的C++代码示例: ```cpp #include #include #include using namespace std; const int N = 55; const int M = N * N; char a[N][N]; int row[N][N], col[N][N]; int R, C; bool vis[M]; int linker[M]; int to[M], nxt[M]; int head[M], tot; int n, m;
void addedge(int u, int v) { ++tot; to[tot] = v; nxt[tot] = head[u]; head[u] = tot; }
bool dfs(int u) { for (int i = head[u]; ~i; i = nxt[i]) { int v = to[i]; if (!vis[v]) { vis[v] = 1; if (linker[v] == -1 || dfs(linker[v])) { linker[v] = u; return 1; } } } return 0; }
int hungary() { int ret = 0; memset(linker, -1, sizeof(linker)); for (int i = 1; i <= R; ++i) { memset(vis, 0, sizeof(vis)); if (dfs(i)) ++ret; } return ret; }
int main() { while (~scanf("%d %d", &n, &m)) { memset(row, 0, sizeof(row)); memset(col, 0, sizeof(col)); memset(head, -1, sizeof(head)); tot = -1; R = C = 0; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { cin >> a[i][j]; if (a[i][j] == '*') { if (row[i][j - 1]) row[i][j] = row[i][j - 1]; else row[i][j] = ++R; if (col[i - 1][j]) col[i][j] = col[i - 1][j]; else col[i][j] = ++C; } } for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (a[i][j] == '*') addedge(row[i][j], col[i][j]); printf("%d\n", hungary()); } return 0; } ``` 来源:https://www.cnblogs.com/bxd123/p/10932872.html