【网络流专题2】 二分图带权最大独立集

Ahead

11.1.2018

例题

网络流24题 方格取数

对网格黑白分点,可以看出每取一个黑点造成的影响是四周的白点不能取
建立超级源汇 对源点向黑点建边 边权为点权 对每一个白点向汇点建边,边权为点权,中间对每一个黑点向会影响到的白点建一条无穷大的边

开始时假设所有的点都取,那么现在就是对修改后的图进行删边似的约束条件成立。即中间inf的边上不能有流量,而这就转化成了原图的最小割问题

代码

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

inline int read()
{
  int x=0;
  char c=getchar();
  while(c<'0' || c>'9') c=getchar();
  while(c<='9' && c>='0')
  {
    x=(x<<3)+(x<<1)+c-'0';
    c=getchar();
  }
  return x;
}

const int N = 5100,inf=0x3f3f3f3f;
int fx[4]= {0,0,1,-1},fy[4]= {1,-1,0,0};

int n,m,s,t,ans;

int to[N*N],nxt[N*N],last[N],len=1,w[N*N];
inline void ins(int x,int y,int c)
{
  to[++len]=y,nxt[len]=last[x],last[x]=len;
  w[len]=c;
}

int h[N];
bool bfs(int s,int t)
{
  queue <int> q;
  memset(h,0,sizeof(h));
  q.push(s);
  h[s]=1;
  while(!q.empty())
  {
    int x=q.front();
    q.pop();
    for(int k=last[x]; k; k=nxt[k])
    {
      int y=to[k];
      if(w[k] && !h[y])
      {
        h[y]=h[x]+1;
        if(y==t) return true;
        q.push(y);
      }
    }
  }
  return false;
}

int dfs(int x,int fl)
{
  if(x==t) return fl;
  int res=fl;
  for(int k=last[x]; k; k=nxt[k])
  {
    int y=to[k];
    if(w[k] && h[y]==h[x]+1)
    {
      int tmp=dfs(y,min(w[k],res));
      w[k]-=tmp;
      w[k^1]+=tmp;
      res-=tmp;
      if(res==0) break;
    }
  }
  if(res==fl) h[x]=0;
  return fl-res;
}

inline int dinic()
{
  int res=0;
  while(bfs(s,t))
  {
    int tmp=dfs(s,inf);
    if(tmp)
    {
      res+=tmp;
      tmp=dfs(s,inf);
    }
  }
  return res;
}

inline void _clear()
{
  len=1,ans=0;
  memset(last,0,sizeof(last));
}

int main()
{
  int x,id;
  while(scanf("%d%d",&n,&m)!=EOF)
  {
    _clear();
    s=n*m+1,t=n*m+2;
    for(int i=1; i<=n; ++i)
      for(int j=1; j<=m; ++j)
      {
        x=read();
        ans+=x;
        id=(i-1)*m+j;
        if((i+j)&1) ins(s,id,x),ins(id,s,0);
        else ins(id,t,x),ins(t,id,0);
      }
    for(int i=1; i<=n; ++i)
      for(int j=1; j<=m; ++j)
        if((i+j)&1)
          for(int k=0; k<4; ++k)
          {
            int t1=i+fx[k],t2=j+fy[k];
            if(t1<=0 || t1>n || t2<=0 || t2>m) continue;
            id=(i-1)*m+j;
            ins(id,(t1-1)*m+t2,inf),ins((t1-1)*m+t2,id,0);
          }
    printf("%d\n",ans-dinic());
  }

  return 0;
}
posted @ 2018-11-01 14:56  PiCaHor  阅读(217)  评论(0编辑  收藏  举报