【bzoj3698】XWW的难题 有上下界的网络流

源点S向每一行连一条容量为(a[i][n],a[i][n]+1)的边
每一列向汇点T连一条容量为(a[n][i],a[n][i]+1)的边
行i向列j连一条容量为(a[i][j],a[i][j]+1)的边

求最大流


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<iostream>
#define maxn 210
#define maxm 100010
#define inf 1000000000

using namespace std;

int head[maxn],to[maxm],c[maxm],next[maxm],q[maxn],d[maxn],in[maxn],cnt[maxn];
double a[maxn][maxn];
int n,m,num,s,t,S,T,ans;

void addedge(int x,int y,int z)
{
	num++;to[num]=y;c[num]=z;next[num]=head[x];head[x]=num;
	num++;to[num]=x;c[num]=0;next[num]=head[y];head[y]=num;
}

bool bfs()
{
	memset(d,-1,sizeof(d));
	int l=0,r=1;
	q[1]=S;d[S]=0;
	while (l<r)
	{
		int x=q[++l];
		for (int p=head[x];p;p=next[p])
		  if (c[p] && d[to[p]]==-1)
		  {
		  	d[to[p]]=d[x]+1;
		  	q[++r]=to[p];
		  }
	}
	if (d[T]==-1) return 0; else return 1;
}

int find(int x,int low)
{
	if (x==T || low==0) return low;
	int totflow=0;
	for (int p=head[x];p;p=next[p])
	  if (c[p] && d[to[p]]==d[x]+1)
	  {
	  	int a=find(to[p],min(c[p],low));
	  	c[p]-=a;c[p^1]+=a;
	  	low-=a;totflow+=a;
	  	if (low==0) return totflow;
	  }
	if (low) d[x]=-1;
	return totflow;
}

void Dinic()
{
	int ans=0;
	while (bfs()) ans+=find(S,inf);
}

bool check(int x)
{
	num=1;s=0;t=2*n+1;S=t+1;T=S+1;
	memset(head,0,sizeof(head));
	memset(in,0,sizeof(in));
	memset(cnt,0,sizeof(cnt));
	in[s]+=x;in[t]-=x;addedge(t,s,inf);
	for (int i=1;i<n;i++)
	{
		if (a[i][n]!=(int)a[i][n]) addedge(s,i,1);
		in[s]-=(int)a[i][n];in[i]+=(int)a[i][n];
	}
	for (int i=1;i<n;i++)
	{
		if (a[n][i]!=(int)a[n][i]) addedge(i+n,t,1);
		in[i+n]-=(int)a[n][i];in[t]+=(int)a[n][i];
	}
	for (int i=1;i<n;i++)
	  for (int j=1;j<n;j++)
	  {
	  	if (a[i][j]!=(int)a[i][j]) addedge(i,j+n,1);
	  	in[i]-=(int)a[i][j];in[j+n]+=(int)a[i][j];
	  }
	for (int i=s;i<=t;i++)
	  if (in[i]>0) cnt[i]=num+1,addedge(S,i,in[i]);
	  else if (in[i]<0) cnt[i]=num+1,addedge(i,T,-in[i]);
	Dinic();
	for (int i=s;i<=t;i++)
	  if (cnt[i] && c[cnt[i]]) return 0;
	return 1;
}

int main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	  for (int j=1;j<=n;j++)
	    scanf("%lf",&a[i][j]);
	int l=0,r=inf,ans=-1;
	while (l<=r)
	{
		int mid=(l+r)/2;
		if (check(mid)) ans=mid,l=mid+1; else r=mid-1;
	}
	if (ans==-1) printf("No\n");
	else printf("%d\n",ans*3);
	return 0;
}


你可能感兴趣的:(【bzoj3698】XWW的难题 有上下界的网络流)