[网络流24题]方格取数

分析

先对棋盘黑白染色(这是常见套路),我们发现,如果选了一个黑点,那相邻的白点就不能选,反之同理

出现了冲突关系,考虑最大权闭合子图

把黑点看成正权点,白点看成负权点,黑点向相邻白点连边,跑最大权闭合子图即可

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define maxc 205
#define maxn 50005
#define maxm 500005 
#define INF 0x3f3f3f3f
using namespace std;
int n,m;
int a[maxc][maxc];
int mark[maxc][maxc];

struct edge{
    int from;
    int to;
    int next;
    int flow;
}E[maxm<<1];
int sz=1;
int head[maxn]; 
void add_edge(int u,int v,int w){
//	printf("%d->%d %d\n",u,v,w); 
    sz++;
    E[sz].from=u;
    E[sz].to=v;
    E[sz].flow=w;
    E[sz].next=head[u];
    head[u]=sz;
    
    sz++;
    E[sz].from=v;
    E[sz].to=u;
    E[sz].flow=0;
    E[sz].next=head[v];
    head[v]=sz;
}

int deep[maxn];
bool bfs(int s,int t){
    queue<int>q;
    q.push(s);
    for(int i=s;i<=t;i++) deep[i]=0;
    deep[s]=1;
    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(int i=head[x];i;i=E[i].next){
            int y=E[i].to;
            if(E[i].flow&&!deep[y]){
                deep[y]=deep[x]+1;
                q.push(y);
                if(y==t) return 1;
            }
        }
    }
    return 0;
}

int dfs(int x,int t,int minf){
    if(x==t) return minf;
    int k,rest=minf;
    for(int i=head[x];i;i=E[i].next){
        int y=E[i].to;
        if(E[i].flow&&deep[y]==deep[x]+1){
            k=dfs(y,t,min(rest,E[i].flow));
            rest-=k;
            E[i].flow-=k;
            E[i^1].flow+=k;
            if(k==0) deep[y]=0;
            if(rest==0) break;
        }
    }
    return minf-rest;
}

int dinic(int s,int t){
    int nowflow=0,maxflow=0;
    while(bfs(s,t)){
        while(nowflow=dfs(s,t,INF)) maxflow+=nowflow;
    }
    return maxflow;
}

inline int get_id(int x,int y){
	return (x-1)*m+y;
}
const int walkx[4]={1,-1,0,0};
const int walky[4]={0,0,1,-1};

int main(){
	int sum=0;
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if((i+j)%2==1) mark[i][j]=1;
			scanf("%d",&a[i][j]);
			sum+=a[i][j];
		}
	}
	int s=0,t=n*m+1;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(mark[i][j]==1) add_edge(s,get_id(i,j),a[i][j]);
			else add_edge(get_id(i,j),t,a[i][j]);
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(mark[i][j]){
				for(int k=0;k<4;k++){
					int x=i+walkx[k];
					int y=j+walky[k];
					if(x>=1&&y>=1&&x<=n&&y<=m){
						add_edge(get_id(i,j),get_id(x,y),INF);
					} 
				} 
			}
		}
	}
	printf("%d\n",sum-dinic(s,t));
} 
posted @ 2019-02-25 14:53  birchtree  阅读(303)  评论(0编辑  收藏  举报