泥泞的区域

AcWing-377-泥泞的区域open in new window

分析

见《进阶指南》第434页。

实现

#include <iostream>
#include <cstring>
using namespace std;

const int N = 52, M = 2510;
struct edge {
    int to, next;
};
edge e[2 * M];
int idx, head[M];
int n, m;
char a[N][N];
int b[N][N][2];
int ln, rn;
bool mark[M];
int match[M];

void add_edge (int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
bool dfs (int cur) {
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to;
        if (mark[to] == true) continue;
        mark[to] = true;
        if (match[to] == 0 || dfs(match[to]) == true) {
            match[to] = cur;
            return true;
        }
    }
    return false;
}

int main () {
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++ i)
        scanf("%s", a[i] + 1);
    
    ln = rn = 1;
    for (int i = 1; i <= n; ++ i) { // 行泥泞块
        for (int j = 1; j <= m + 1; ++ j) { // m + 1
            if (a[i][j] == '*')
                b[i][j][0] = ln;
            else
                ++ ln;
        }
    }
    -- ln;
    for (int j = 1; j <= m; ++ j) { // 列泥泞块
        for (int i = 1; i <= n + 1; ++ i) {
            if (a[i][j] == '*')
                b[i][j][1] = rn;
            else
                ++ rn;
        }
    }
    -- rn;
    for (int i = 1; i <= n; ++ i) {
        for (int j = 1; j <= m; ++ j) {
            if (a[i][j] == '*') {
                add_edge(b[i][j][0], ln + b[i][j][1]);
                add_edge(ln + b[i][j][1], b[i][j][0]);
            }
        }
    }
    int res = 0;
    for (int i = 1; i <= ln; ++ i) {
        memset(mark, 0, sizeof(mark));
        if (dfs(i) == true) ++ res;
    }
    printf("%d", res);
    return 0;
}
最后修改于: