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

题目

代码

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;
}
相关推荐
艾莉丝努力练剑20 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
还债大湿兄2 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上5 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
Risehuxyc5 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
秋说6 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen7 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove7 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty8 小时前
排序算法(二):插入排序
算法·排序算法