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

题目

代码

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;
}
相关推荐
杜子不疼.8 小时前
【C++ AI 大模型接入 SDK】 - DeepSeek 模型接入(上)
开发语言·c++·chatgpt
石山代码9 小时前
C++ 内存分区 堆区
java·开发语言·c++
心中有国也有家9 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事9 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院9 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet10 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
张小姐的猫11 小时前
【Linux】多线程 —— 线程互斥
linux·运维·服务器·c++
m0_6294947313 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户13 小时前
用队列实现栈
数据结构·算法