【bzoj1738】[Usaco2005 mar]Ombrophobic Bovines 发抖的牛 二分答案+最大流

二分答案
每个牛棚拆成两个点i和i'
源点向每个牛棚i连一条容量为初始数量的边
每个牛棚i向能走到(最短路小于二分的答案)的牛棚j'连一条容量为inf的边
每个牛棚i'向汇点连一条容量为容量的边

最大流


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

using namespace std;

long long f[maxn][maxn];
int a[maxn],b[maxn];
int head[1100],to[maxm],c[maxm],next[maxm],q[1010],d[1010];
int n,m,num,s,t,ans,sum;

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(low,c[p]));
	  	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()
{
	while (bfs()) ans+=find(s,inf);
}

bool check(long long x)
{
	memset(head,0,sizeof(head));
	num=1;s=0;t=2*n+1;ans=0;
	for (int i=1;i<=n;i++) addedge(s,i,a[i]),addedge(n+i,t,b[i]);
	for (int i=1;i<=n;i++)
	  for (int j=1;j<=n;j++)
	    if (f[i][j]<=x) addedge(i,j+n,inf);
	Dinic();
	if (ans==sum) return 1; else return 0;
}

int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<=n;i++) {scanf("%d%d",&a[i],&b[i]);sum+=a[i];}
	for (int i=1;i<=n;i++)
	  for (int j=1;j<=n;j++)
	    f[i][j]=inf*200ll;
	for (int i=1;i<=m;i++)
	{
		int x,y;
		long long z;
		scanf("%d%d%lld",&x,&y,&z);
		f[x][y]=f[y][x]=min(f[x][y],z);
	}
	for (int i=1;i<=n;i++) f[i][i]=0;
	for (int k=1;k<=n;k++)
	  for (int i=1;i<=n;i++)
	    for (int j=1;j<=n;j++)
	      f[i][j]=min(f[i][j],f[i][k]+f[k][j]);
	long long l=0,r=inf*200ll-1,ans=-1;
	while (l<=r)
	{
		long long mid=(l+r)/2;
		if (check(mid)) ans=mid,r=mid-1; else l=mid+1;
	}
	printf("%lld\n",ans);
	return 0;
}


你可能感兴趣的:(【bzoj1738】[Usaco2005 mar]Ombrophobic Bovines 发抖的牛 二分答案+最大流)