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

题目

代码

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;
}
相关推荐
MobotStone19 分钟前
我的 AI 代码清理方法论:从原型到生产,只需 5 步
算法·程序员·架构
沐苏瑶7 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
ZoeJoy88 小时前
算法筑基(二):搜索算法——从线性查找到图搜索,精准定位数据
算法·哈希算法·图搜索算法
Alicx.9 小时前
dfs由易到难
算法·蓝桥杯·宽度优先
桦09 小时前
【C++复习】:继承
开发语言·c++
_日拱一卒9 小时前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
鱼难终9 小时前
类和对象(下)
c++
云泽8089 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享10 小时前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病10 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和