我们不妨想一想,这道题目又有\(abs\)又有\(Max\)不是很好算对吧.
所以我们二分答案,考虑怎么\(check\).
对于一个点,显然它能够取的范围是\([l,r]\),接着是对于一行一列都有一个限制使得满足题目条件.
然后直接跑上下界可行流即可.
/*
mail: [email protected]
author: MLEAutoMaton
This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define re register
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi(){
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
const int N=20010,Inf=1e9+10;
int ans,cnt,front[N],dep[N],delta[N],s,t,n,m,a[210][210],l,r,ss,tt,cur[N];queue<int>Q;
int lie[210],hang[210];
struct node{int to,nxt,w;}e[N*100];
void Add(int u,int v,int w){
e[cnt]=(node){v,front[u],w};front[u]=cnt++;
e[cnt]=(node){u,front[v],0};front[v]=cnt++;
}
bool bfs(){
Q.push(ss);memset(dep,0,sizeof(dep));dep[ss]=1;
while(!Q.empty()){
int u=Q.front();Q.pop();
for(int i=front[u];~i;i=e[i].nxt){
int v=e[i].to;
if(!dep[v] && e[i].w){
dep[v]=dep[u]+1;Q.push(v);
}
}
}
return dep[tt];
}
int dfs(int u,int flow){
if(!flow || u==tt)return flow;
for(int &i=cur[u];~i;i=e[i].nxt){
int v=e[i].to;
if(dep[v]==dep[u]+1 && e[i].w){
int di=dfs(v,min(flow,e[i].w));
if(di){
e[i].w-=di;e[i^1].w+=di;return di;
}
else dep[v]=0;
}
}
return 0;
}
int Dinic(){
int flow=0;
while(bfs()){
for(int i=0;i<=tt;i++)cur[i]=front[i];
while(int d=dfs(ss,Inf))flow+=d;
}
return flow;
}
int build(int mid){
memset(front,-1,sizeof(front));cnt=0;int sum=0;
memset(delta,0,sizeof(delta));
s=0;t=n+m+1;ss=t+1;tt=ss+1;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
Add(i,j+n,r-l);
delta[i]-=l;delta[j+n]+=l;
}
for(int i=1;i<=n;i++){
int L=hang[i]-mid,R=hang[i]+mid;
Add(s,i,R-L);
delta[s]-=L;delta[i]+=L;
}
for(int i=1;i<=m;i++){
int L=lie[i]-mid,R=lie[i]+mid;
Add(i+n,t,R-L);
delta[t]+=L;delta[i+n]-=L;
}
for(int i=s;i<=t;i++)
if(delta[i]>0)Add(ss,i,delta[i]),sum+=delta[i];
else Add(i,tt,-delta[i]);
Add(t,s,Inf);
return sum;
}
bool check(int mid){
int sum=build(mid);
int flow=Dinic();
return flow>=sum;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in.in","r",stdin);
#endif
n=gi();m=gi();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
a[i][j]=gi();
lie[j]+=a[i][j];hang[i]+=a[i][j];
}
l=gi();r=gi();
int L=0,R=10000000,ret=0;
while(L<=R){
int mid=(L+R)>>1;
if(check(mid)){ret=mid;R=mid-1;}
else L=mid+1;
}
printf("%d\n",ret);
return 0;
}