上下界网络流:http://www.cnblogs.com/kane0526/archive/2013/04/05/3001108.html
二分答案转化为判定问题:构造矩阵,使得每行每列之和分别满足在一个区间内,这就是带上下界网络流判定问题。
s----------------------->i行----------------------->j列----------------------------->t
[si-mid,si+mid] [L,R] [sj-mid,sj+mid]
#include<cstdio> #include<cstdlib> #include<algorithm> #include<cstring> using namespace std; inline char nc() { static char buf[100000],*p1=buf,*p2=buf; if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; } return *p1++; } inline void read(int &x) { char c=nc(),b=1; for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1; for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b; } namespace DINIC{ #define oo 1<<30 #define V G[p].v #define cl(x) memset(x,0,sizeof(x)) #define M 200000+5 #define N 1000+5 struct edge{ int u,v,f; int next; }; edge G[M]; int head[N],num=1; inline void add(int u,int v,int f,int p){ G[p].u=u; G[p].v=v; G[p].f=f; G[p].next=head[u]; head[u]=p; } inline void link(int u,int v,int f){ add(u,v,f,num+=2); add(v,u,0,num^1); } int S,T; int Que[N],l,r; int dis[N]; inline bool bfs(){ int u; memset(dis,-1,sizeof(dis)); cl(Que); l=r=-1; dis[S]=1; Que[++r]=S; while (l<r) { u=Que[++l]; for (int p=head[u];p;p=G[p].next) if (G[p].f && dis[V]==-1) { dis[V]=dis[u]+1; Que[++r]=V; if (V==T) return true; } } return false; } int minimum; int cur[N]; inline bool dfs(int u,int mini){ if (u==T) { minimum=mini; return true; } for (int p=cur[u];p;p=G[p].next) { cur[u]=p; if (G[p].f && dis[V]==dis[u]+1 && dfs(V,min(mini,G[p].f))) { G[p].f-=minimum; G[p^1].f+=minimum; return true; } } dis[u]=-1; return false; } inline int Dinic(){ int ret=0; while (bfs()) { memcpy(cur,head,sizeof(cur)); while (dfs(S,oo)) ret+=minimum; } return ret; } inline void clear(){ cl(G); cl(head); num=1; } } int n,m; int a[205][205]; int sum1[205],sum2[205]; int L,R; int du[405]; inline bool check(int mid) { using namespace DINIC; clear(); int s=n+m+1,t=n+m+2,u,d; S=n+m+3; T=n+m+4; memset(du,0,sizeof(du)); for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) link(i,j+n,R-L),du[j+n]+=L,du[i]-=L; for (int i=1;i<=n;i++) { d=max(0,sum1[i]-mid),u=sum1[i]+mid; link(s,i,u-d); du[i]+=d; du[s]-=d; } for (int j=1;j<=m;j++) { d=max(0,sum2[j]-mid),u=sum2[j]+mid; link(j+n,t,u-d); du[t]+=d; du[j+n]-=d; } link(t,s,oo); int icnt=0,itmp; for (int i=1;i<=n+m+2;i++) if (du[i]>0) link(S,i,du[i]),icnt+=du[i]; else link(i,T,-du[i]); itmp=Dinic(); if (itmp<icnt) return false; return true; } int main() { int _L,_R,_M; freopen("t.in","r",stdin); freopen("t.out","w",stdout); read(n); read(m); for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) read(a[i][j]),sum1[i]+=a[i][j],sum2[j]+=a[i][j]; read(L); read(R); _L=-1; _R=2000000; while (_L+1<_R) if (check(_M=(_L+_R)>>1)) _R=_M; else _L=_M; printf("%d\n",_R); return 0; }