luoge P2774 方格取数问题(最小割)
题目大意
在一个有 m*n 个方格的棋盘中,每个方格中有一个正整数。现要从方格中取数,使任意 2 个数所在方格没有公共边,且取出的数的总和最大。试设计一个满足要求的取数算法。对于给定的方格棋盘,按照取数要求编程找出总和最大的数。
解题思路
对棋盘中的点进行黑白染色,将所有(i+j)为奇数的划分到白色,为偶数的划分到黑色,所有白色的点向其四周连容量为无限大的边,源点向白色点连容量为权值的边,黑色点向汇点连容量为权值的边,总的边权减去最小割即是答案。
可行性:因为黑白点之间连接的是容量无限大的边,因此,不可能被割去,所有一旦选择了一个点,则其四周的点九不能被选择了
AC代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define int long long
const int maxn=505;
const int maxm=5e5+5;
const int inf=0x3f3f3f3f;
struct Edge{
int to,nxt,cap,flow;
}edge[maxm];
int tol;
int head[maxn];
void init(){
tol=2;
memset(head,-1,sizeof(head));
}
void AddEdge(int u,int v,int w,int rw=0){
edge[tol].to=v;edge[tol].cap=w;edge[tol].flow=0;
edge[tol].nxt=head[u];head[u]=tol++;
edge[tol].to=u;edge[tol].cap=rw;edge[tol].flow=0;
edge[tol].nxt=head[v];head[v]=tol++;
}
int Q[maxn];
int dep[maxn],cur[maxn],sta[maxn];
bool bfs(int s,int t,int n){
int front=0,tail=0;
memset(dep,-1,sizeof(dep[0])*(n+1));
dep[s]=0;
Q[tail++]=s;
while(front<tail){
int u=Q[front++];
for(int i=head[u];i!=-1;i=edge[i].nxt){
int v=edge[i].to;
if(edge[i].cap>edge[i].flow&&dep[v]==-1){
dep[v]=dep[u]+1;
if(v==t) return true;
Q[tail++]=v;
}
}
}
return false;
}
int dinic(int s,int t,int n){
int maxflow=0;
while(bfs(s,t,n)){
for(int i=0;i<n;i++) cur[i]=head[i];
int u=s,tail=0;
while(cur[s]!=-1){
if(u==t){
int tp=inf;
for(int i=tail-1;i>=0;i--)
{
tp=min(tp,edge[sta[i]].cap-edge[sta[i]].flow);
}
maxflow+=tp;
for(int i=tail-1;i>=0;i--){
edge[sta[i]].flow+=tp;
edge[sta[i]^1].flow-=tp;
if(edge[sta[i]].cap-edge[sta[i]].flow==0) tail=i;
}
u=edge[sta[tail]^1].to;
}
else if(cur[u]!=-1&&edge[cur[u]].cap>edge[cur[u]].flow&&dep[u]+1==dep[edge[cur[u]].to]){
sta[tail++]=cur[u];
u=edge[cur[u]].to;
}
else{
while(u!=s&&cur[u]==-1) u=edge[sta[--tail]^1].to;
cur[u] = edge [cur[u]].nxt;
}
}
}
return maxflow;
}
int a[105][105];
int n,m;
inline int Hash(int x,int y){return (x-1)*m+y;}
inline void connect(int u,int v,bool col)
{
if(col) AddEdge(u,v,inf);
else AddEdge(v,u,inf);
}
int32_t main()
{
init();
scanf("%lld%lld",&n,&m);
int s=0,t=n*m+1;
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%lld",&a[i][j]);
ans+=a[i][j];
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if((i+j)&1) AddEdge(s,Hash(i,j),a[i][j]);else AddEdge(Hash(i,j),t,a[i][j]);
if(i+1<=n) connect(Hash(i,j),Hash(i+1,j),(i+j)&1);
if(i-1>=1) connect(Hash(i,j),Hash(i-1,j),(i+j)&1);
if(j-1>=1) connect(Hash(i,j),Hash(i,j-1),(i+j)&1);
if(j+1<=m) connect(Hash(i,j),Hash(i,j+1),(i+j)&1);
}
}
printf("%lld\n",ans-dinic(s,t,t+1));
}