棋盘覆盖 最大流求解最大匹配
一个二分图最大匹配的问题,依然是分成两部分,数字坐标和为奇数的为一部分,和为偶数的为另一部分。这两部分各自内部没有连线,可以作为二分图。
二分图最大匹配可以用最大流解决。可以引进一个源点 s s s,从 s s s出发向二分图的左部分连线(有向边),把从左部分连向右部分的双向边换成从左连向右边的单向边,然后从二分图的右部分的每个点出发,连向汇点 t t t,图中所有边的权值都是1,这样一个图就建好了。
然后跑一边~~沙(Sand)盒(Box)~~的Dinic,最大流量就是答案。
#include <bits/stdc++.h>
using namespace std;
int n, T, s, t;
const int N = 110, inf = 0x3f3f3f3f;
#define mem(a, b) memset(a, b, sizeof a)
int head[101000], nex[101000], to[101000], ed[101000], cnt;
bool can[N][N];
void pre(){
mem(head, -1);
mem(nex, -1);
cnt = 1;
mem(can, true);
s = 12000;
t = 12001;
}
void add(int a, int b, int c){
to[++cnt] = b, nex[cnt] = head[a], head[a] = cnt, ed[cnt] = c;
to[++cnt] = a, nex[cnt] = head[b], head[b] = cnt, ed[cnt] = 0;
}
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
int d[101000];
int cur[101000];
bool bfs(){
mem(d, 0);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cur[(i - 1) * 110 + j] = head[(i - 1) * 110 + j];
cur[s] = head[s];
cur[t] = head[t];
queue<int > q;
q.push(s);
d[s] = 1;
while (q.size()){
int tp = q.front();
q.pop();
for (int i = head[tp]; ~i; i = nex[i]){
int y = to[i];
if (!d[y] && ed[i]){
d[y] = d[tp] + 1;
if (y == t)return 1;
q.push(y);
}
}
}
return 0;
}
int dinic(int x, int f){
if (x == t || f == 0)return f;
int r = f, k;
for (int i = cur[x]; ~i; i = nex[i]){
cur[x] = i;
if (d[x] + 1 == d[to[i]] && ed[i]){
k = dinic(to[i], min(f, ed[i]));
if (!k){
d[to[i]] = 0;
}
r -= k;
ed[i] -= k;
ed[i ^ 1] += k;
if (r == 0)break;
}
}
return f - r;
}
int maxflow(){
int flow = 0;
while (bfs()){
flow += dinic(s, inf);
}
return flow;
}
int main(){
pre();
scanf("%d %d", &n, &T);
while (T--){
int x, y;
scanf("%d %d", &x, &y);
can[x][y] = 0;
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (can[i][j]){
if ((i + j) & 1){
add(s, (i - 1) * 110 + j, 1);
for (int k = 0; k < 4; k++){
int x = i + dx[k];
int y = j + dy[k];
if (x >= 1 && x <= n && y >= 1 && y <= n && can[x][y]){
add((i - 1) * 110 + j, (x - 1) * 110 + y, 1);
}
}
}
else {
add((i - 1) * 110 + j, t, 1);
}
}
}
}
printf("%d\n", maxflow());
return 0;
}
作者: correct
出处:https://www.cnblogs.com/correct/p/16548408.html
本站使用「CC BY 4.0」创作共享协议,转载请在文章明显位置注明作者及出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话