【棋盘覆盖——匈牙利算法】

题目

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 110;
int g[N][N], st[N][N];
PII match[N][N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n, t;
bool find(PII u)
{
    for(int i = 0; i < 4; i++)
    {
        int x = u.x + dx[i], y = u.y + dy[i]; //遍历心仪女生
        if(x < 1 || y < 1 || x > n || y > n || g[x][y] || st[x][y]) continue;
        st[x][y] = 1; //指这次处理之后归宿确定(不可再次考虑)
        if(match[x][y].x == -1 || find(match[x][y])) //名花无主或者皆大欢喜
        {
            match[x][y] = u; //匹配
            return true; //报喜
        }
    }
    
    return false;
}
int main()
{
    cin >> n >> t;
    for(int i = 1; i <= t; i++)
    {
        int a, b;
        cin >> a >> b;
        g[a][b] = 1;
    }
    
    memset(match, -1, sizeof match);
    int ans = 0;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            if((i + j) % 2 || g[i][j]) continue;
            memset(st, 0, sizeof st);
            if(find({i, j})) ans++;
        }
    }
    
    cout << ans;
}
相关推荐
沐怡旸1 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥2 小时前
C++ 内存管理
c++
聚客AI2 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v4 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工6 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农8 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了8 小时前
AcWing学习——双指针算法
c++·算法
感哥8 小时前
C++ 指针和引用
c++
moonlifesudo8 小时前
322:零钱兑换(三种方法)
算法
感哥19 小时前
C++ 多态
c++