【BZOJ2132】圈地计划

这是一道我当场做出来的题。

题面

https://www.lydsy.com/JudgeOnline/problem.php?id=2132

https://www.luogu.org/problemnew/show/P1935

题解

黑白染色+最小割(和上一题hapeness几乎一样)

#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#define ri register int
#define N 50000
#define INF 1000000007
#define S 0
#define T (n*m+1)
using namespace std;

int n,m,x,sum=0;


struct graph {
  vector<int> to,w;
  vector<int> ed[N];
  int cur[N],d[N];
  void add_edge(int u,int v,int w1) {
    to.push_back(v); w.push_back(w1); ed[u].push_back(to.size()-1);
    to.push_back(u); w.push_back(0);  ed[v].push_back(to.size()-1);
  }
  void add_edges(int u,int v,int w1) {
    to.push_back(v); w.push_back(w1); ed[u].push_back(to.size()-1);
    to.push_back(u); w.push_back(w1);  ed[v].push_back(to.size()-1);
  }
  bool bfs() {
    queue<int> q;
    memset(d,0x3f,sizeof(d));
    d[0]=0; q.push(0);
    while (!q.empty()) {
      int x=q.front(); q.pop();
      for (ri i=0,l=ed[x].size();i<l;i++) {
        int e=ed[x][i];
        if (w[e] && d[x]+1<d[to[e]]) {
          d[to[e]]=d[x]+1;
          q.push(to[e]);
        }
      }
    }
    return d[T]<INF;
  }
  int dfs(int x,int limit) {
    if (x==T || !limit) return limit;
    int tot=0;
    for (ri &i=cur[x];i<ed[x].size();i++) {
      int e=ed[x][i];
      if (d[to[e]]==d[x]+1 && w[e]) {
        int f=dfs(to[e],min(limit,w[e]));
        if (!f) continue;
        w[e]-=f; w[1^e]+=f; 
        tot+=f; limit-=f;
        if (!limit) return tot;
      }
    }
    return tot;
  }
  int dinic() {
    int ret=0;
    while (bfs()) {
      memset(cur,0,sizeof(cur));
      ret+=dfs(S,INF);
    }
    return ret;
  }
} G;

int main(){
  cin>>n>>m;
  for (ri i=1;i<=n;i++) {
    for (ri j=1;j<=m;j++) {
      cin>>x; sum+=x;
      if ((i+j)%2==0) {
        G.add_edge(S,(i-1)*m+j,x);
      }
      else {
        G.add_edge((i-1)*m+j,T,x);
      }
    }
  }
  
  for (ri i=1;i<=n;i++) {
    for (ri j=1;j<=m;j++) {
      cin>>x; sum+=x;
      if ((i+j)%2==1) {
        G.add_edge(S,(i-1)*m+j,x);
      }
      else {
        G.add_edge((i-1)*m+j,T,x);
      }
    }
  }
  
  for (ri i=1;i<=n;i++) {
    for (ri j=1;j<=m;j++) {
      cin>>x;
      if (i<n) G.add_edges((i-1)*m+j,i*m+j,x),sum+=x;
      if (i>1) G.add_edges((i-1)*m+j,(i-2)*m+j,x),sum+=x;
      if (j<m) G.add_edges((i-1)*m+j,(i-1)*m+j+1,x),sum+=x;
      if (j>1) G.add_edges((i-1)*m+j,(i-1)*m+j-1,x),sum+=x;
    }
  }
  
  cout<<sum-G.dinic()<<endl;
}

 

posted @ 2019-07-15 15:27  HellPix  阅读(169)  评论(0编辑  收藏  举报