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

题目

代码

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;
}
相关推荐
QUST-Learn3D19 分钟前
PCL绘制点云+法线
c++
云格~41 分钟前
Leetcode:1. 两数之和
数据结构·算法·leetcode
几点才到啊1 小时前
C语言实现冒泡排序:算法原理与代码解析
c语言·算法·排序算法
xxjiaz1 小时前
水果成篮--LeetCode
java·算法·leetcode·职场和发展
binary思维1 小时前
C语言实现贪心算法
c语言·算法·贪心算法
PingdiGuo_guo1 小时前
C++动态分配内存知识点!
开发语言·c++
阿沁QWQ1 小时前
STL中emplace实现原理是什么?
c++
fpcc1 小时前
设计心得——数据结构的意义
数据结构·c++
Echo``1 小时前
12:图像处理—Blob分析+边缘提取
图像处理·算法·计算机视觉·视觉检测