二分图 : 匈牙利算法

棋盘覆盖

匈牙利算法

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 110;
int n, m;
PII match[N][N];
bool g[N][N], st[N][N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

bool find(int x, int y) {
    for (int i = 0; i < 4; ++i) {
        int a = x + dx[i], b = y + dy[i];
        if (a && a <= n && b && b <= n && !g[a][b] && !st[a][b]) {
            st[a][b] = true;
            PII t = match[a][b];
            if (t.x == -1 || find(t.x, t.y)) {
                match[a][b] = {x, y};
                return true;
            }
        }
    }
    return false;
}


int main() {
    IO; 
    cin >> n >> m;
    while (m--) {
        int x, y;
        cin >> x >> y;
        g[x][y] = 1;
    }
    memset(match, -1, sizeof match);
    int res = 0;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
            if ((i + j) % 2 && !g[i][j]) { //只要枚举一半
                memset(st, 0, sizeof st);
                if (find(i, j)) ++res;
            }
    cout << res << '\n';
    return 0;
}

posted @ 2021-02-22 17:05  phr2000  阅读(48)  评论(0编辑  收藏  举报