# [网络流24题] 09 方格取数问题 (二分图点权最大独立集，最小割)

38 篇文章 0 订阅

<问题分析>

<建模方法>

①：从s向X集合中每个顶点连接一条边，容量为格子中数值。
②：从Y集合中每个顶点向t连接一条边，容量为格子中数值。
③：相邻黑白格子Xi,Yj之间，从Xi向Yj连接一条边，容量为INF。

<建模分析>

#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
#define Max(a,b) ((a)>(b)?(a):(b))
using namespace std;

const int N=910, M=9010000, INF= 0x3f3f3f3f;
int n, m, s, t, top;
int head[N], gap[N], cur[N], dis[N], pre[N], flag[N], vis[N], num[35][35];
int dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0};

struct Edge{
int to, next, flow;
Edge(int _to = 0, int _next = 0, int _flow = 0):to(_to), next(_next), flow(_flow){}
}edge[M];

void Addedge(int from, int to, int flow){
}

void Bfs(){
queue<int> q;
memset(gap, 0, sizeof(gap));
memset(dis, -1, sizeof(dis));
dis[t] = 0, gap[0] = 1; q.push(t);
while(!q.empty()){
int u = q.front(); q.pop();
for(int i = head[u]; i+1; i = edge[i].next){
if(dis[edge[i].to] == -1){
dis[edge[i].to] = dis[u] + 1;
gap[dis[edge[i].to]] ++;
q.push(edge[i].to);
}
}
}
}

int Sap(){
Bfs();
memset(pre, -1, sizeof(pre));
for(int i = s; i <= t; ++i) cur[i] = head[i];
int u = s, cur_flow, max_flow = 0, neck, tmp;
while(dis[s] <= t){
if(u == t){
cur_flow = INF;
for(int i = s; i != t; i = edge[cur[i]].to){
if(cur_flow > edge[cur[i]].flow){
cur_flow = edge[cur[i]].flow;
neck = i;
}
}
for(int i = s; i != t; i = edge[cur[i]].to){
tmp = cur[i];
edge[tmp].flow -= cur_flow;
edge[tmp^1].flow += cur_flow;
}
max_flow += cur_flow;
u = neck;
}
int i;
for(i = cur[u]; i + 1; i = edge[i].next)
if(edge[i].flow && dis[u] == dis[edge[i].to] + 1) break;
if(i != -1){
cur[u] = i;
pre[edge[i].to] = u;
u = edge[i].to;
}else{
if(--gap[dis[u]] == 0) break;
int mindis = t;
for(int i = head[u]; i + 1; i = edge[i].next)
if(edge[i].flow && mindis > dis[edge[i].to]) mindis = dis[edge[i].to];
dis[u] = mindis + 1;
gap[dis[u]]++;
if(u != s) u = pre[u];
}
}
return max_flow;
}

int main(){
freopen("grid.in", "r", stdin);
freopen("grid.out", "w", stdout);
scanf("%d%d", &n, &m);
top = s = 0; t = n * m + 1;
int sum = 0;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
scanf("%d", &num[i][j]);
sum += num[i][j];
if((i + j) % 2 == 0) Addedge(s, (i-1)*m+j, num[i][j]);
}
}
int x, y;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
if((i + j) % 2) continue;
for(int k = 0; k < 4; ++k){
x = i + dx[k], y = j + dy[k];
if(x < 1 || x > n || y < 1 || y > m) continue;
if((i + j) % 2 == 0) Addedge((i-1)*m+j, (x-1)*m+y, INF);
}
}
}
printf("%d\n", sum - Sap());
}

02-16 6739
08-25 231
03-19 662
03-19 554
08-22 689
07-19 465
06-12 889
12-14 364
06-08 440

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

Ac-try

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。